1

I'm trying to save a file using GDI+, but I just get a "A generic error occurred in GDI+" exception. The code works fine for almost every photo but this one (we handle thousands a day for years and this is the first I've heard of it). I think it might have something to do with exif data or perhaps something else odd from the photographers camera or editor.

Here's the photo in question

And here is code to reproduce the error with this photo:

class Program
{
    static void Main(string[] args)
    {
        using (var img = Image.FromFile("Err.jpg"))
        using (var ms = new MemoryStream())
        {
            img.Save(ms, ImageFormat.Jpeg);
        }
    }
}

How am I supposed to handle this in GDI+? Is there a way to strip out the extra stuff that is causing the problem?

4

2 回答 2

0

您的图像的 exif 配置文件似乎是问题所在。当我删除它时,我可以将图像保存到内存流中。我使用Magick.NET删除了 exif 配置文件。

using (MagickImage magickImage = new MagickImage())
{
  using (var magickStream = new MemoryStream())
  {
    magickImage.Read(@"gdi_err.jpg");
    magickImage.Strip();
    magickImage.Write(magickStream);
    magickStream.Position = 0;

    // This part is just here to demonstrate that saving the image works.
    // You don't need it because magickStream already contains the data you want.
    using (Image image = Image.FromStream(magickStream))
    {
      using (var ms = new MemoryStream())
      {
        image.Save(ms, ImageFormat.Jpeg);
      }
    }
  }
}
于 2013-06-23T09:07:46.540 回答
0

似乎首先将图像转换为bmp可以解决问题。找到一种更有效的方法会很好(不需要创建多个图像并将其加载到内存中),但这是迄今为止我发现的最好的方法。

static void Main(string[] args)
{
    var path = @"gdi_err.jpg";
    using (var img1 = Image.FromFile(path))
    using (var ms1 = new MemoryStream())
    {
        img1.Save(ms1, ImageFormat.Bmp);
        ms1.Position = 0;
        using (var img2 = Image.FromStream(ms1))
        using (var ms2 = new MemoryStream())
        {
            img2.Save(ms2, ImageFormat.Jpeg);
        }
    }
}
于 2013-06-18T23:59:30.257 回答