A generic error occurred in GDI+, JPEG Image to MemoryStream

前端 未结 30 1518
再見小時候
再見小時候 2020-11-22 06:47

This seems to be a bit of an infamous error all over the web. So much so that I have been unable to find an answer to my problem as my scenario doesn\'t fit. An exception ge

30条回答
  •  攒了一身酷
    2020-11-22 07:19

    I also got this error when saving JPEGs, but only for certain images.

    My final code:

      try
      {
        img.SaveJpeg(tmpFile, quality); // This is always successful for say image1.jpg, but always throws the GDI+ exception for image2.jpg
      }
      catch (Exception ex)
      {
        // Try HU's method: Convert it to a Bitmap first
        img = new Bitmap(img); 
        img.SaveJpeg(tmpFile, quality); // This is always successful
      }
    

    I didn't create the images so I can't tell what the difference is.
    I'd appreciate if anyone could explain that.

    This is my SaveJpeg function just FYI:

    private static void SaveJpeg(this Image img, string filename, int quality)
    {
      EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, (long)quality);
      ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
      EncoderParameters encoderParams = new EncoderParameters(1);
      encoderParams.Param[0] = qualityParam;
      img.Save(filename, jpegCodec, encoderParams);
    }
    
    private static ImageCodecInfo GetEncoderInfo(string mimeType)
    {
        var encoders = ImageCodecInfo.GetImageEncoders();
        var encoder = encoders.SingleOrDefault(c => string.Equals(c.MimeType, mimeType, StringComparison.InvariantCultureIgnoreCase));
        if (encoder == null) throw new Exception($"Encoder not found for mime type {mimeType}");
        return encoder;
    }
    

提交回复
热议问题