我知道已经有很多关于此的帖子,但到目前为止我尝试过的所有解决方案都失败了。我想要的是从 Image
对象获取 Byte[]
。
到目前为止我尝试了什么:
使用 (MemoryStream ms = new MemoryStream()){/*...*/}
(GDI+ 异常)- 处理
图像
的副本 (ArgumentNullException (Encoder)) - 关注 solution from Microsoft (ArgumentNullException (编码器))
- 使用
ImageConverter
(GDI+ 异常)
我希望拥有的东西:
public static Byte[] BytesFromImage(Image img) {
Byte[] imgFile;
MemoryStream ms = new MemoryStream();
img.Save(ms, img.RawFormat);
imgfile = ms.ToArray();
return imgFile;
}
每次我得到一个错误,它来自 img.save(ms, img.RawFormat);
。
也许只有我一个人是这样,但我在 StackOverflow 上遵循的所有解决方案都给了我相同的结果:一个 GDI+ 错误以及如此好的解释。
最佳答案
将 img.RawFormat
替换为 ImageFormat.Bmp
示例:
class Program
{
public static byte[] BytesFromImage(Image img)
{
Byte[] imgFile;
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Bmp);
imgFile = ms.ToArray();
return imgFile;
}
private static void Main(string[] args)
{
using (Image image = new Bitmap(100, 100))
{
byte[] imgArr = BytesFromImage(image);
Console.WriteLine("Image size is: {0}", imgArr.Length);
}
}
关于c# - 将图像转换为字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16722135/