1

I am using ImageProcessor to process images in my website.

I have this resize function:

 public Image ResizePhoto6version(Image img, int width, int height)
    {
        using (var ms = new MemoryStream())
        {
            using (var imgf = new ImageFactory(false))
            {
                imgf.Load(img)
                    .Resize(new ResizeLayer(new Size(width, height), ResizeMode.Max))
                    .Save(ms);

                return Bitmap.FromStream(ms);
            }
        }
    }

In the webservice, I run this code:

MemoryStream ytSmallStream = new MemoryStream();
MemoryStream ytMediumStream = new MemoryStream();
System.Drawing.Image ytSmallThumb = null;
System.Drawing.Image ytMediumThumb = null;

ytSmallThumb.Save(ytSmallStream, ImageFormat.Jpeg);
ytSmallStream.Position = 0;

ytMediumThumb.Save(ytMediumStream, ImageFormat.Jpeg);
ytMediumStream.Position = 0;

I get an exception when it reached the Save function ytSmallThumb.Save():

A generic error occurred in GDI+

The image is returned correctly from ResizeThumbnailToSmall function and the Stream has information of the image with the right size.

Liron Harel
  • 10,819
  • 26
  • 118
  • 217
  • I'm pretty sure your problem is that `FromStream` requires the underlying stream to remain open, yet is being disposed in the `ResizePhoto6version` method (by way of the `using`). From MSDN: "You must keep the stream open for the lifetime of the Image." https://msdn.microsoft.com/en-us/library/93z9ee4x(v=vs.110).aspx#Remarks – pinkfloydx33 Jul 11 '18 at 08:48
  • 1
    Possible duplicate of [Image.Save(..) throws a GDI+ exception because the memory stream is closed](https://stackoverflow.com/questions/336387/image-save-throws-a-gdi-exception-because-the-memory-stream-is-closed) – pinkfloydx33 Jul 11 '18 at 08:50
  • @pinkfloydx33 I will try that, so I should convert to bytes instead and return that? – Liron Harel Jul 11 '18 at 08:52
  • 1
    No, just remove the first `using` from the `ResizePhoto6version` method (leave it simply as `var ms=new MemoryStream();`) . It's a memory stream, no *need* to dispose it really. See Jon's answer in the duplicate; just make sure to `Dispose` *the bitmap/image* when you're done and it will close the stream for you – pinkfloydx33 Jul 11 '18 at 08:57
  • @pinkfloydx33 correct! Thank you. – Liron Harel Jul 11 '18 at 09:05
  • @pinkfloydx33Would you write an answer and I accept? – Liron Harel Jul 11 '18 at 09:10
  • No because this is a duplicate. Perhaps there is a better one then the dupe I suggested, but either way this question will eventually get closed... Its been asked and answered many times before. – pinkfloydx33 Jul 11 '18 at 09:12

1 Answers1

1

ImageProcessor makes me crazy today, it throws "A generic error occurred in GDI+" exception everytime I resize PNG files. and after Recycle the application pool I don't see the exception anymore.

Hope it help.

Nick Hoàng
  • 417
  • 2
  • 6