代码之家  ›  专栏  ›  技术社区  ›  Ves

C#.Net调用具有特定像素格式的Graphics.FromImage(myBitmap)时抛出内存不足异常

  •  1
  • Ves  · 技术社区  · 6 年前

    我正在创建一个小工具来做一些图标绘制,我遇到了一个错误,我找不到一个解释。我选择的第一个像素格式导致内存不足异常(我选择了列表中第一个带有Alpha通道的:Format16bppArgb1555)。 简单地改成列表中的下一个alpha格式就解决了我的问题,但是我很好奇为什么会出错,所以我决定测试所有的像素格式。文档中说有许多格式不起作用,但这两种格式似乎应该起作用。

    为什么 Format16bppArgb1555 Format16bppGrayScale 调用Graphics.FromImage()时导致内存不足异常?

        Bitmap myBitmap=null;
        Graphics myGraphics=null;
    
        foreach ( PixelFormat pixFormat in Enum.GetValues(typeof(System.Drawing.Imaging.PixelFormat)))
        {
            Console.WriteLine();
            try
            {
                myBitmap = new Bitmap(192, 192, pixFormat);
                Console.WriteLine("Good Bitmap" + PixFormatToString(pixFormat));
                myGraphics = Graphics.FromImage(myBitmap);
    
            }
            catch( Exception e)
            {
                if (myBitmap == null)
                {
                    Console.WriteLine("Bad Bitmap " + PixFormatToString(pixFormat));
                    Console.WriteLine(e.Message);
                }
                else
                {
                    Console.WriteLine("Bad Graphics " + PixFormatToString(pixFormat));
                    Console.WriteLine(e.Message);
                }
    
            }
            finally
            {
                if (myBitmap != null)
                    myBitmap.Dispose();
                if (myGraphics != null)
                    myGraphics.Dispose();
                myBitmap = null;
                myGraphics = null;
            }
        }
    

    以下是压缩输出:

    UNEXPECTED ERRORS:
    Bad Graphics Format16bppArgb1555
    Out of memory.
    
    Bad Graphics Format16bppGrayScale
    Out of memory.
    
    
    Expected Errors Bad Bitmaps(not valid to use these PixelFormats for Bitmaps):
    Undefined,Max,Indexed,Gdi,Alpha,PAlpha,Extended,Canonical
    
    Expected Errors Bad Graphics(cannot create graphics from indexed formats):
    BitmapFormat1bppIndexed,BitmapFormat4bppIndexed,Format8bppIndexed
    
    Good Bitmaps and Graphics:
     BitmapFormat16bppRgb555
     BitmapFormat16bppRgb565
     BitmapFormat24bppRgb
     BitmapFormat32bppRgb
     BitmapFormat32bppPArgb
     BitmapFormat32bppArgb
     BitmapFormat48bppRgb
     BitmapFormat64bppPArgb
     BitmapFormat64bppArgb
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Ves    6 年前

    @pinkfloydx33在其评论中给出了解决方案:

    从文档:如果图像具有以下任何像素格式,此方法也会引发异常。。。格式16bppargb1555格式16bppgrayscale

    docs.microsoft.com/en-us/dotnet/api/

    GDI+不支持这些格式,并且没有足够的错误代码来处理原因,因此它抛出“内存不足”