This tip describes how to change the alpha value of an image to make it
appear blended. There's also an example MIDlet with source code.
In MIDP 2.0 there's a new method in the Image class,
getRGB(...)
that will get all Alpha, Red, Green, Blue (ARGB) values from the image
to an int array. We can use this method, and the resulting array, to
change the alpha value of the image.
Integers in J2ME are four bytes, each pixel in the image is described
by the ARGB values where each color is one byte 0 to 255. If the alpha
value is 0, the corresponding pixel will be transparent, if the alpha
is 255, the pixel will be opaque.
To get a specific color from the int array, it's possible to use the
AND '&' operator and to accomplish the blending effect we need to get the colors, without the alpha value, from the int array.
FF = 11111111 = 255
0xFFFFFFFF - Alpha = 255, Red =255 Green = 255, Blue = 255
(0xFFFFFFFF & 0x00FFFFFF) = 0x00FFFFFF
By doing this we'll only get the RGB colors from the int array, alpha equals zero.
Now when we just have the RGB colors and alpha equals zero, we can just add our new alpha value.
If we have the alpha value 255 and want to add this to our color, we need to use the shift left operator.
To change:
(00000000 00000000 00000000 11111111) to
(11111111 00000000 00000000 00000000)
use the shift left '<<' operator.
(0xFF << 24) = 0xFF000000.
With this knowledge we now can change the alpha value or do masking for specific colors.
- Use the getRGB(...) method in the image class to get all the ARGB values from the image to a int array.
- Use the blend function below to change the alpha value for each value in the array.
- Use the createRGBImage(...) method in the image class to create a new image from the edited int array.
There are examples on how to use the getRGB and createRGBImage methods in the MIDlet below.
public static void blend(int[] raw, int alphaValue){
int len = raw.length;
// Start loop through all the pixels in the image.
for(int i=0; i<len; i++){
int a = 0;
int color = (raw[i] & 0x00FFFFFF); // get the color of the pixel.
a = alphaValue; // set the alpha value we want to use 0-255.
a = (a<<24); // left shift the alpha value 24 bits.
// if color = 00000000 11111111 11111111 00000000 (0xFFFF00 = Yellow)
// and alpha= 01111111 00000000 00000000 00000000
// then c+a = 01111111 11111111 11111111 00000000
// and the pixel will be blended.
color += a;
raw[i] = color;
}
}
example code