将图像转换为ByteArray
本文关键字:ByteArray 转换 图像 | 更新日期: 2023-09-27 18:14:59
我知道已经有很多关于这个的帖子了,但是到目前为止我尝试的每一个解决方案都失败了。我想从一个Image
对象中得到一个Byte[]
。
我已经试过了:
-
using (MemoryStream ms = new MemoryStream()){/*...*/}
(GDI+ Exception) - 正在处理
image
的副本(ArgumentNullException (Encoder)) - 遵循Microsoft (ArgumentNullException (Encoder)) 的解决方案
- 使用
ImageConverter
(GDI+ Exception)
我的期望:
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);
}
}