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

标签 c# image exception arrays gdi+

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

相关文章:

c# - 在编辑个人资料页面中提交表单时,文本框值保持不变

c# - Marketplace 测试套件返回 "Unsupported API cannot be used by background agent"

java - 使用 iText 将图像添加到 PDF

java - 将 RGB 数据的 byte[] 转换为图像

html - 我的 srcset 定义有问题,还是当前的浏览器支持很弱?

c# - 如何区分 .Net 中的单击和双击?

c# - VSTO加载项CustomTaskPane升级到Word 2016/2019后将自行打开

java - 如何解决AES加密代码中的异常

c# - 具有不抛出保证的 IEnumerable 扩展

java - Play Framework CompilationException