2

Related topic (without solution yet): Access to raw data in ARGB_8888 Android Bitmap

In short: when using copyPixelFromBuffer and copyPixelsToBuffer, Android already applied the Alpha channel on the RGB channels.

I need to convert it into original ARGB value and vice-versa. I don't know how does Android apply it. Can you please tell me the formula?

Community
  • 1
  • 1
Luke Vo
  • 17,859
  • 21
  • 105
  • 181

1 Answers1

4

Android stores Bitmap data in alpha premultiplied form. In other words, the alpha value is not applied when the data is copied, it has been applied all the time.

To convert into premultiplied form, multiply the color components with the normalized alpha value, like this:

redPremultiplied   = red   * normalizedAlpha
greenPremultiplied = green * normalizedAlpha
bluePremultiplied  = blue  * normalizedAlpha
alphaPremultiplied = alpha

where

red             = <value between 0 and 255>
green           = <value between 0 and 255>
blue            = <value between 0 and 255>
alpha           = <value between 0 and 255>
normalizedAlpha = alpha / 255

To convert from premultiplied alpha to canonical form, divide the premultiplied components with the normalized alpha:

red   = redPremultiplied   / normalizedAlpha
green = greenPremultiplied / normalizedAlpha
blue  = bluePremultiplied  / normalizedAlpha
alpha = alphaPremultiplied

but be sure to watch out for normalizedAlpha = 0! You should note though that the data handled by Bitmap.copyPixelsToBuffer() and Bitmap.copyPixelsFromBuffer()in theory can be in any format. It is safer to use Bitmap.getPixels() and Bitmap.setPixels(), because the API makes guarantees about the format of the data handled by those functions. In particular, you don't have to worry about premultiplying and un-premultiplying the alpha, because those functions handle that for you.

Martin Nordholts
  • 10,338
  • 2
  • 39
  • 43
  • The purpose of not using `getPixel()` and `setPixel()` is to access a lots of pixels, so using buffer has a huge better performance. I'll test your formula and tell you the result later. Thank you. – Luke Vo Sep 07 '12 at 13:16