Search code examples
crgbpixeldepthlibpng

libpng, c code, how to convert RGB value to pixel value?


I am using libpng for C, I am new to image processing.

I use png_get_IHDR() to get the width, height, color_type and bit_depth, the values I got for an image are:

color_type = 6 (PNG_COLOR_TYPE_RGB_ALPHA)
bit_depth = 8
width = 1850
height = 2048

I use png_get_channels() to get the channels which is 4
I use png_get_rowbytes() to get the bytes per row which is 7400 (1850*4)
I use png_read_image() to get all the image data

My aim is to convert the RGB values to pixel value, that's all ! I know the R, G, B and Alpha values of each pixel are stored orderly in the image data buffer, seems the conversion methods are different for different bit_depth. Also can I ignore Alpha value, only use R, G, B values when doing the conversion? Anyone can help? Thanks!


Solution

  • If you don't want to worry about differences due to color_type and bit_depth, and always want to ignore the alpha channel, use

    png_set_expand(png_ptr);
    png_set_strip_16(png_ptr);
    if (color_type & PNG_COLOR_MASK_ALPHA)
       png_set_strip_alpha(png_ptr);
    

    Then your rows will always contain 8-bit R,G,B, R,G,B ... samples, one group of three bytes per pixel, "width" groups per row.

    If you are building with libpng-1.5.6 or later, you can use "png_set_scale_16(png_ptr)" instead; it scales 16-bit samples down to 8-bit more accurately.