首页 > 解决方案 > 当字节数组的源是 jpg 时,从存储的字节数组创建位图并保存到磁盘会引发 GDI+ 异常

问题描述

我希望有人可以帮助解决我将已提供给我的图像保存为字节数组的问题。

版本:

故事是

  1. 用户上传图片
  2. 我们序列化成一个字节数组并存储它
  3. 稍后我们获取该字节数组并创建一个内存流,并使用该流创建一个位图对象。
  4. 使用该位图对象保存到磁盘

当原始文件为 PNG 格式时,这一切都有效。但是,当它是 Jpg 格式时它会失败。

下面是一些示例代码,您可以将其粘贴在基本控制台应用程序中,只要您引用 System.Drawing,它就会运行。

static void Main(string[] args)
{
    Console.WriteLine("Enter image file location");
    var filePath = Console.ReadLine();
    while (!File.Exists(filePath))
    {
        Console.WriteLine("Cannot find file. Try Again");
        filePath = Console.ReadLine();
    }

    byte[] bytes = File.ReadAllBytes(filePath);

    Bitmap image;
    using (var stream = new MemoryStream(bytes))
    {
        image = new Bitmap(stream);
    }

    WriteToFile(image);
    image.Dispose();
    Console.ReadKey();
}

private static void WriteToFile(Bitmap image)
{
    Console.WriteLine("Enter write location filename");
    var fileName = Console.ReadLine();
    image.Save(fileName);
    Console.WriteLine($"File saved to {fileName}");
}

如果原始图像是 PNG,则可以正常工作,如果是 JPG,则失败。这是为什么?我看到位图类的 Save 方法有一个需要ImageFormat实例的重载。但是只有我拥有的是原始字节数组,所以我不知道我的图像格式是什么。

任何帮助将不胜感激,谢谢!

编辑:我尝试将图像格式指定为 JPG,无论是从原始文件创建字节数组还是将其保存回磁盘(参见下面的代码),但使用 jpgs 时它仍然会继续失败。但是,Pngs 仍然可以正常工作

static void Main(string[] args)
{
    Console.WriteLine("Enter jpg file location");
    var filePath = Console.ReadLine();
    while (!File.Exists(filePath))
    {
        Console.WriteLine("Cannot find file. Try Again");
        filePath = Console.ReadLine();
    }

    byte[] bytes = CreateSerializedImage(filePath);

    Image image;
    using (var steram = new MemoryStream(bytes))
    {
        image = Image.FromStream(steram);
    }

    WriteToFile(image);
    image.Dispose();
    Console.ReadKey();
}

private static byte[] CreateSerializedImage(string filePath)
{
    var image = Image.FromFile(filePath);
    using (var stream = new MemoryStream())
    {
        image.Save(stream,ImageFormat.Jpeg);
        return stream.ToArray();
    }
}

private static void WriteToFile(Image image)
{
    Console.WriteLine("Enter write location filename");
    var fileName = Console.ReadLine();
    image.Save(fileName, ImageFormat.Jpeg);
    Console.WriteLine($"File saved to {fileName}");
}

标签: c#bitmappngjpeg

解决方案


您在MemoryStream写入图像之前处理,请尝试在文件保存后处理流。这对我有用:)

如果要获取图像格式,请尝试从流的前几个字节中检测它:

维基百科:文件签名列表


推荐阅读