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

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

    This is an expansion / qualification of Fred's response which stated: "GDI limits the height of an image to 65534". We ran into this issue with one of our .NET applications, and having seen the post, our outsourcing team raised their hands in the air and said they couldn't fix the problem without major changes.

    Based on my testing, it's possible to create / manipulate images with a height larger than 65534, but the issue arises when saving to a stream or file IN CERTAIN FORMATS. In the following code, the t.Save() method call throws our friend the generic exception when the pixel height is 65501 for me. For reasons of curiosity, I repeated the test for width, and the same limit applied to saving.

        for (int i = 65498; i <= 100000; i++)
        {
            using (Bitmap t = new Bitmap(800, i))
            using (Graphics gBmp = Graphics.FromImage(t))
            {
                Color green = Color.FromArgb(0x40, 0, 0xff, 0);
                using (Brush greenBrush = new SolidBrush(green))
                {
                    // draw a green rectangle to the bitmap in memory
                    gBmp.FillRectangle(greenBrush, 0, 0, 799, i);
                    if (File.Exists("c:\\temp\\i.jpg"))
                    {
                        File.Delete("c:\\temp\\i.jpg");
                    }
                    t.Save("c:\\temp\\i.jpg", ImageFormat.Jpeg);
                }
            }
            GC.Collect();
        }
    

    The same error also occurs if you write to a memory stream.

    To get round it, you can repeat the above code and substitute ImageFormat.Tiff or ImageFormat.Bmp for ImageFormat.Jpeg.

    This runs up to heights / widths of 100,000 for me - I didn't test the limits. As it happens .Tiff was a viable option for us.

    BE WARNED

    The in memory TIFF streams / files consume more memory than their JPG counterparts.

提交回复
热议问题