【问题标题】:JPEG manipulations and dotnet - GDI+ exceptionJPEG 操作和 dotnet - GDI+ 异常
【发布时间】:2012-02-16 18:15:27
【问题描述】:

例如,这里是示例 JPEG,我无法保存(!)但可以使用标准 dotnet 类读取(例如找出宽度和高度)。原始文件:

http://dl.dropbox.com/u/5079317/184809_1_original.jpg

在 Windows 图像编辑器中保存相同的图像后,一切正常: http://dl.dropbox.com/u/5079317/184809_1_resaved.jpg

我很久以前就注意到了这个错误,但这不是主要问题。但是在当前的项目中,我有数千张这样的图像,我真的需要某种解决方案。

可以使用哪些第三方库?

这是我的阅读方式:

public ImageFile SaveImage(HttpPostedFileBase file, string fileNameWithPath, bool splitImage, out string errorMessage)
{
  try
  {
    using (var stream = file.InputStream)
    {
      using (Image source = Image.FromStream(stream))
      {
        return SaveImage(source, fileNameWithPath, splitImage, out errorMessage);
        // which actually do source.Save(fileNameWithPath, ImageFormat.Jpeg);
        // Exception: A generic error occurred in GDI+.
      }
    }
  }
  catch (Exception e)
  ...
}

【问题讨论】:

    标签: .net image jpeg


    【解决方案1】:

    我不确定您为 SaveImage 使用的库,但如果您只是使用 .NET,请在 Image 对象上调用以下 Save 方法(返回类型为 void),并返回您需要的任何对象在新文件中的 System.Drawing.Image 对象上。

    source.Save(@"C:\{path}\184809_1_resaved.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
    

    没有更多细节,这是我能提供的最好的,因为我不知道 ImageFile 类的实现是什么样的。 ImageFile 是您当前的返回类型,但我只是更改了类型以使其正常工作。

    public System.IO.Stream SaveImage(HttpPostedFileBase file, string fileNameWithPath, bool splitImage, out string errorMessage)
    {
        try
        {
            using (var stream = file.InputStream)
            {
                using (System.Drawing.Image source = System.Drawing.Image.FromStream(stream))
                {
                    source.Save(@"C:\resaved.jpg", ImageFormat.Jpeg);
                    source.Save(stream, ImageFormat.Jpeg);
                    stream.Position = 0;
                    errorMessage = string.Empty;
                    return stream;
                }
            }
        }
        catch (Exception e)
        {
            errorMessage = e.Message.ToString();
        }
        return null;
    }
    

    【讨论】:

      【解决方案2】:

      Iirc 某些格式需要查找,并非所有流都支持。您可以尝试在内存流中缓冲:

      using (var input = file.InputStream)
      using (var buffer = new MemoryStream())
      {
          input.CopyTo(buffer);
          buffer.Position = 0; // rewind
          using (Image source = Image.FromStream(buffer))
          { ... Etc  as before ... }
      }
      

      【讨论】:

        【解决方案3】:

        将原始图像调整为相同大小可以解决问题:

        Image img2 = FixedSize(source, source.Width, source.Height, true);
        img2.Save(path, ImageFormat.Jpeg);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-21
          • 1970-01-01
          • 2020-10-25
          • 1970-01-01
          • 2010-10-26
          • 2010-10-02
          • 2013-08-24
          相关资源
          最近更新 更多