views:

162

answers:

1

below is my code which throws exception because i am using the 'using' statement with the memory stream, i.e. it gets disposed at the end and when i try to save the image it throws the exception.

using(MemoryStream memoryStream = new MemoryStream())
  {
    ImageCodecInfo imageEncoder = GetEncoderInfo("image/jpeg");
    EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);
    EncoderParameters encodeParams = new EncoderParameters(1);
    encodeParams.Param[0] = qualityParam;

    using (Bitmap bitmapImage = new Bitmap(image, width, height))
    {
        bitmapImage.SetResolution(dpi, dpi);
        bitmapImage.Save(memoryStream, imageEncoder, encodeParams);
    }

    Image compressedImage = new Bitmap(memoryStream);
  }
  _compressedImage.Save("C:\\test.jpg");
A: 

GDI+ doesn't always load the image into memory, but defers this operation (same thing happens when you create images from handles, such as icons). If you want to make sure that the bitmap is kept in memory, create a bitmap and draw the other onto the new bitmap.

Unfortunately, this is not well documented, and I have been struggeling with such issues before. Internally, it is a call to GdipCreateBitmapFromStream in the flat GDI+ API.

Here is a statement from MS (newsgroup post by John Hornick).

Lucero