Skip to content Skip to sidebar Skip to footer

Puzzled By Pixel Value In Bitmap (pre Multiplied Color Using Setpixel)

I cannot explain this (screenshot from Eclipse debug): Pixel at (0,0) does not have the values it was set for! All other pixels are fine, they do have the same value they were a

Solution 1:

Well, more or less I found what is happening. It is called "pre-multiplied Alpha" and Bitmaps before api19 do not offer any way to control this feature, they are premultiplied by default and this cannot be changed. On api19 there are 2 new methods to Bitmap: isPremultiplied() and setPremultiplied(boolean) According to the new doc:

When a pixel is pre-multiplied, the RGB components have been multiplied by the alpha component. For instance, if the original color is a 50% translucent red (128, 255, 0, 0), the pre-multiplied form is (128, 128, 0, 0).

Also this post and this other post give some more explanation. According to this, some more tests show:

Bitmapsource= Bitmap.createBitmap(2, 2, Config.ARGB_8888);
    source.setPixel(0, 0, Color.argb(0x02, 0x10, 0x20, 0x30));
    source.setPixel(0, 1, Color.argb(0x03, 0x10, 0x20, 0x30));
    source.setPixel(1, 0, Color.argb(0x05, 0x78, 0x96, 0x64));
    source.setPixel(1, 1, Color.argb(128, 255, 200, 150));

    intsp00= source.getPixel(0, 0); // sp00   33554432 [0x2000000]    intsp01= source.getPixel(0, 1); // sp01   50331733 [0x3000055]    intsp10= source.getPixel(1, 0); // sp10   90610022 [0x5669966]    intsp11= source.getPixel(1, 1); // sp11   -2130720875 [0x80ffc795]

For lower color values the rounding causes the info to be lost (see sp00 above). Also, for lower values, the value of alpha itself is not retrieved to the original. On top of this, the given formulas do not explain the values I see.

Finally to use unmodified pixels I now use this code to set the Bitmap pixles:

Bitmapsource= Bitmap.createBitmap(2, 2, Config.ARGB_8888);
    IntBufferdata= IntBuffer.wrap(newint[] {
            Color.argb(0x06, 0xff, 0xa0, 0x8d),
            Color.argb(0x2a, 0xab, 0xce, 0x9f),
            Color.argb(0x8f, 0xfe, 0x05, 0x18),
            Color.argb(0xff, 0xc8, 0xcf, 0xd4)
    });
    source.copyPixelsFromBuffer(data);

and to retrieve the pixels I use:

IntBuffersourceData= IntBuffer.allocate(4);
    source.copyPixelsToBuffer(sourceData);

Using these methods do not premultiply the color.

Post a Comment for "Puzzled By Pixel Value In Bitmap (pre Multiplied Color Using Setpixel)"