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

前端 未结 30 1375
再見小時候
再見小時候 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:10

    Save image to bitmap variable

    using (var ms = new MemoryStream())
    {
        Bitmap bmp = new Bitmap(imageToConvert);
        bmp.Save(ms, format);
        return ms.ToArray();
    }
    
    0 讨论(0)
  • 2020-11-22 07:14

    My turn!

    using (System.Drawing.Image img = Bitmap.FromFile(fileName))
    {
          ... do some manipulation of img ...
          img.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    

    Got it on the .Save... because the using() is holding the file open, so I can't overwrite it. Maybe this will help someone in the future.

    0 讨论(0)
  • 2020-11-22 07:14

    I notice that your "jpeg" case is actually:

                default:
                    format = ImageFormat.Jpeg;
                    break;
    

    Are you sure that the format is jpeg and not something else?

    I'd try:

                case "image/jpg": // or "image/jpeg" !
                    format = ImageFormat.Jpeg;
                    break;
    

    Or check what imageToConvert.MimeType() is actually returning.

    UPDATE

    Is there any other initialisation you need to do to the MemoryStream object?

    0 讨论(0)
  • 2020-11-22 07:14

    Simple, create a new instance of Bitmap solves the problem.

    string imagePath = Path.Combine(Environment.CurrentDirectory, $"Bhatti{i}.png");
    Bitmap bitmap = new Bitmap(image);
    bitmap.Save(imagePath);
    
    0 讨论(0)
  • 2020-11-22 07:15

    We had a similar problem on generating a PDF or resize image using ImageProcessor lib on production server.

    Recycle the application pool fix the issue.

    0 讨论(0)
  • 2020-11-22 07:15
    byte[] bts = (byte[])page1.EnhMetaFileBits; 
    using (var ms = new MemoryStream(bts)) 
    { 
        var image = System.Drawing.Image.FromStream(ms); 
        System.Drawing.Image img = image.GetThumbnailImage(200, 260, null, IntPtr.Zero);      
        img.Save(NewPath, System.Drawing.Imaging.ImageFormat.Png);
    }
    
    0 讨论(0)
提交回复
热议问题