views:

193

answers:

4

Good Day,

I have some small transparent gif images (under 100x100) and wrote the following code to iterate through all the pixels to give me the RGB values:

private void IteratePixels(string filepath)
{
    string dataFormat = String.Empty;
    Bitmap objBitmap = new Bitmap(filepath);
    int counter = 0;
    for (int y = 0; y < objBitmap.Height; y++)
    {
        for (int x = 0; x < objBitmap.Width; x++)
        {
            Color col = objBitmap.GetPixel(x, y);
            dataFormat = String.Format("{0} => Red: {1:x} Green: {2:x} Blue: {3:x}",
                counter++, col.R, col.G, col.B);
            System.Diagnostics.Debug.WriteLine(dataFormat);

            // Perform an operation on the Color value here.
            // objBitmap.SetPixel(x, y, col);
        }
    }


}

The code works (albeit slow because of the GetPixel and the string formatting) but what I was most surprised at was that the output is reporting that the transparent pixels are black! I wonder why?

0 => Red: 0 Green: 0 Blue: 0
1 => Red: 0 Green: 0 Blue: 0 ...

Now let's say if I did have a transparent gif image with a black background covering 25% of the image's area, how would I know whether the pixel is tranparent or black?

TIA,

coson

+2  A: 

You should check the alpha channel of the Color structure, instead of the red, green or blue channels.

Lasse V. Karlsen
+2  A: 

Sorry I can't provide a detailed answer, but GIF stores colors in a palette (basically, array) with up to 256 entries, not by RGB value. So transparency is associated with an element in the array and not a specific color. You could have rgb(0,0,0) assigned to a different position in the palette, allowing both transparency and pure black.

James M.
+4  A: 

Images really have 4 attributes: Red, Green, Blue, and Alpha.

Alpha is how transparent an area is. GIF images only support transparent/not transparent, unlike other formats like PNG that have full alpha support, so you can do things like have 40% transparent pixels.

You can access it with col.A in your code above.

For reference, the MSDN Color structure is http://msdn.microsoft.com/en-us/library/system.drawing.color.aspx

McPherrinM
A: 

Keeping in mind the other helpful answers, once you start thinking in terms of the alpha value at each pixel, how could you tell the difference between completely transparent black, completely transparent blue, orange, or yellow? They aren't really different when you draw them on top of any existing pixels: the colors below are unchanged when you paint a (perfectly) transparent coat over them. If those transparent pixels in your gif come back black in your looping code, then that is only because it is a common, reasonable default, to set all memory values to zero (R=0, G=0, B=0, A=0) ---which is "transparent black" (on some level).

Jared Updike