我正在创建一个用于绘制图标的小工具,但遇到一个错误,找不到解释。我选择的第一个PixelFormat导致内存不足异常。 (我选择了Alpha通道列表中的第一个:Format16bppArgb1555)。 只需更改列表中的下一个alpha格式即可解决我的问题,但是我很好奇为什么会出现错误,因此我决定测试所有PixelFormats。文档说有很多格式无法使用,但是这两种格式似乎应该使用。
为什么在调用Graphics.FromImage()时Format16bppArgb1555
和Format16bppGrayScale
导致内存不足异常?
这是我编写的测试代码:
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
答案 0 :(得分:0)
@ pinkfloydx33在他的评论中有解决方案:
从文档中:如果图像具有以下任何像素格式,则此方法也会引发异常... Format16bppArgb1555 Format16bppGrayScale
由于某些原因,它们显然不受GDI +支持。 docs.microsoft.com/en-us/dotnet/api/…
GDI +不支持这些格式,并且没有足够的错误代码来处理原因,因此它抛出“内存不足”