How to query the bit depth of a PNG?

梦想的初衷 提交于 2019-12-22 23:42:29

问题


I have a PNG file which has 8-bit color depth as evidenced by file properties:

Yes, when I open the file

var filePath = "00050-w600.png";
var bitmap = new Bitmap(filePath);
Console.WriteLine(bitmap.PixelFormat);

I get Format32bppArgb. I also looked in the PropertyIdList and PropertyItems properties but didn't see anything obvious.

So how do I extract the Bit Depth from the PNG?

P.S. None of the framework methods seem to work. System.Windows.Media.Imaging.BitmapSource might work but it's only in WPF and .NET Core 3. I need this for .NET 4.x and .NET Core 2.x.

P.P.S. I just needed to know whether the PNG is 8 bit or not, so I wrote a sure fire method to check if anyone needs it - should work in any framework.

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.

来源:https://stackoverflow.com/questions/55978230/how-to-query-the-bit-depth-of-a-png

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!