Ang*_*ker 5 .net c# png system.drawing .net-core
我有一个 PNG 文件,文件属性证明它具有 8 位颜色深度:
是的,当我打开文件时
var filePath = "00050-w600.png";
var bitmap = new Bitmap(filePath);
Console.WriteLine(bitmap.PixelFormat);
Run Code Online (Sandbox Code Playgroud)
我明白了Format32bppArgb。我还查看了PropertyIdList和PropertyItems属性,但没有看到任何明显的东西。
那么如何从 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;
}
}
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)