我有一个具有 8 位颜色深度的 PNG 文件,如文件属性所示:
是的,当我打开文件时
var filePath = "00050-w600.png";
var bitmap = new Bitmap(filePath);
Console.WriteLine(bitmap.PixelFormat);
我明白了Format32bppArgb
。我还查看了PropertyIdList
andPropertyItems
属性,但没有看到任何明显的东西。
那么如何从 PNG 中提取位深度呢?
PS 框架方法似乎都不起作用。 System.Windows.Media.Imaging.BitmapSource
可能工作,但它只在 WPF 和 .NET Core 3 中。我需要这个用于 .NET 4.x 和 .NET Core 2.x。
PPS 我只需要知道 PNG 是否为 8 位,所以我写了一个确定的方法来检查是否有人需要它 - 应该在任何框架中工作。
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.