我有一个PNG文件,其颜色深度为8位,这由文件属性证明:
是的,当我打开文件
var filePath = "00050-w600.png";
var bitmap = new Bitmap(filePath);
Console.WriteLine(bitmap.PixelFormat);
我得到Format32bppArgb
。我还查看了PropertyIdList
和PropertyItems
属性,但看不到任何明显的内容。
那么我该如何从PNG中提取位深度?
P.S。框架方法似乎都不起作用。 System.Windows.Media.Imaging.BitmapSource
可能有效,但仅在WPF和.NET Core 3中有效。对于.NET 4.x和.NET Core 2.x,我需要使用它。
P.P.S。我只需要知道PNG是否为8位,所以我写了一个确定的fire方法来检查是否有人需要-应该在任何框架中工作。
public static bool IsPng8BitColorDepth(string filePath)
{
const int COLOR_TYPE_BITS_8 = 3;
const int COLOR_DEPTH_8 = 8;
int startReadPosition = 24;
int colorDepthPositionOffset = 0;
int colorTypePositionOffset = 1;
try
{
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
fs.Position = startReadPosition;
byte[] buffer = new byte[2];
fs.Read(buffer, 0, 2);
int colorDepthValue = buffer[colorDepthPositionOffset];
int colorTypeValue = buffer[colorTypePositionOffset];
return colorDepthValue == COLOR_DEPTH_8 && colorTypeValue == COLOR_TYPE_BITS_8;
}
}
catch (Exception)
{
return false;
}
}
Color Allowed Interpretation
Type Bit Depths
0 1,2,4,8,16 Each pixel value is a grayscale level.
2 8,16 Each pixel value is an R,G,B series.
3 1,2,4,8 Each pixel value is a palette index;
a PLTE chunk must appear.
4 8,16 Each pixel value is a grayscale level,
followed by an alpha channel level.
6 8,16 Each pixel value is an R,G,B series,
followed by an alpha channel level.