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

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

    I'll add this cause of the error as well in hopes it helps some future internet traveler. :)

    GDI+ limits the maximum height of an image to 65500

    We do some basic image resizing, but in resizing we try to maintain aspect ratio. We have a QA guy who's a little too good at this job; he decided to test this with a ONE pixel wide photo that was 480 pixels tall. When the image was scaled to meet our dimensions, the height was north of 68,000 pixels and our app exploded with A generic error occurred in GDI+.

    You can verify this yourself with test:

      int width = 480;
      var height = UInt16.MaxValue - 36; //succeeds at 65499, 65500
      try
      {
        while(true)
        {
          var image = new Bitmap(width, height);
          using(MemoryStream ms = new MemoryStream())
          {
            //error will throw from here
            image.Save(ms, ImageFormat.Jpeg);
          }
          height += 1;
        }
      }
      catch(Exception ex)
      {
        //explodes at 65501 with "A generic error occurred in GDI+."
      }
    

    It's too bad there's not a friendly .net ArgumentException thrown in the constructor of Bitmap.

提交回复
热议问题