gpt4 book ai didi

c# - 将图像转换为字节数组

转载 作者:太空宇宙 更新时间:2023-11-03 16:13:17 26 4
gpt4 key购买 nike

我知道已经有很多关于此的帖子,但到目前为止我尝试过的所有解决方案都失败了。我想要的是从 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com