How to differentiate between a pixel with no color and a black pixel?

1.3k views Asked by At

I am using ChunkyPNG in order to get the colors of pixels on images. When an image has no background color at all, and is rendered into a browser, the background color will become white (usually, depending on your browser configuration).

My problem is that, when analyzing the pixels with ChunkyPNG, the values of a pixel that has no color at all is rgb(0,0,0), and the value of a pixel that is black is rgb(0,0,0). Is there any way I can differentiate between those? Checking opacity or... What am I missing?

Here is my code:

chunky_image = ChunkyPNG::Image.from_file("test.png")

width = chunky_image.dimension.width
height = chunky_image.dimension.height
(0..width - 1).each do |x|
  (0..height- 1).each do |y|
    red = ChunkyPNG::Color.r(chunky_image[x,y])
    green = ChunkyPNG::Color.g(chunky_image[x,y])
    blue = ChunkyPNG::Color.b(chunky_image[x,y])
    p "red: " + red.to_s
    p "green: " + green.to_s
    p "ble: " + blue.to_s
  end
end
2

There are 2 answers

0
Marcel Blanck On BEST ANSWER

You need to the rgba value instead of the rgb value.

if r,g,b is 0 and a is 255 it is solid black

if r,g,b is 0 and a is > 0 but < 255 it is still black but more or less transparent

if a is 0, no matter what r,g,b it is full transparent (no color in your words)

So what you miss is the Color.a(pixel) value. Hopefully your picture has COLOR_TRUECOLOR_ALPHA

0
MxLDevs On

When an image has no background color at all, and is rendered into a browser, the background color will become white (usually, depending on your browser configuration).

"No background" is usually achieved through a 4th color channel to encode the opacity of the pixel. Image formats such as PNG support alpha channels while others such as the standard JPEG do not. Most modern browsers will correctly render the transparent pixels such that you will see whatever is "under" the image (could be the background color of the page, some text, etc.)

The actual color of the pixel can be anything, but they are usually a single, solid color for optimization purposes (eg: compression in the case of PNG). For example, Imagemagick uses white, while Paint.NET uses black. Of course, if your image renderer properly supports alpha channels then it will draw the pixel properly.

I'm not sure what you want to do with the pixel data but you can use ChunkyPNG::Color.a to fetch the value of the alpha channel. An a value of 0 means it's fully transparent, while 255 means it's fully opaque.