开发者

A generic error occurred in GDI+ when closing the memory stream or using 'using' with memory stream

开发者 https://www.devze.com 2022-12-11 17:41 出处:网络
below is my code which throws exception because i a开发者_JAVA技巧m 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 th

below is my code which throws exception because i a开发者_JAVA技巧m 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");


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

0

精彩评论

暂无评论...
验证码 换一张
取 消