.net JPEG操作和dotnet-GDI+异常

.net JPEG操作和dotnet-GDI+异常,.net,image,jpeg,.net,Image,Jpeg,例如,这里是我无法保存的示例JPEG!但可以阅读,例如使用标准的dotnet类查找宽度和高度。原始文件: 在windows图像编辑器中保存相同的图像后,所有操作都非常有效: 我很久以前就注意到了这个bug,但它不是什么大问题。但在目前的项目中,我有数千张这样的图片,我真的需要某种解决方案 可以使用哪些第三方库 以下是我的阅读方式: public ImageFile SaveImage(HttpPostedFileBase file, string fileNameWithPath, bool

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

在windows图像编辑器中保存相同的图像后,所有操作都非常有效:

我很久以前就注意到了这个bug,但它不是什么大问题。但在目前的项目中,我有数千张这样的图片,我真的需要某种解决方案

可以使用哪些第三方库

以下是我的阅读方式:

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,请在图像对象上使用void返回类型调用以下Save方法,并根据新文件中的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;
}

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 ... }
}

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

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