×
Namespaces

Variants
Actions
Revision as of 09:25, 26 September 2012 by hamishwillee (Talk | contribs)

How to change image colors (on the fly) in Java ME.

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Article
Created: reflexus@ig.com.br (21 Jun 2011)
Last edited: hamishwillee (26 Sep 2012)

This article provides a method to change image colors (on the fly) in Java ME.

  // by George Roberto Peres (JavaMan).reflexus@ig.com.br  
public Image imageColor(Image image, int color) {
// create array to hold the image data
int[] rgbData = new int[image.getWidth() * image.getHeight()];
// Obtains ARGB pixel data from the specified region of this image and stores
// it in the provided array of integers
image.getRGB(rgbData, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
int pixel;
int alpha;
int red;
int green;
int blue;
// loop through all pixels and ajust colors
for (int i = 0; i < rgbData.length; i++) {
pixel = rgbData[i];
alpha = (pixel & 0xff000000) >> 24;
red = (pixel & 0x00ff0000) >> 16;
green = (pixel & 0x0000ff00) >> 8;
blue = (pixel & 0x000000ff);
// change colors. those are some examples
switch (color) {
case 1: green += 8; red += 16; blue += 128; break;
case 2: green += 96; red += 24; blue += 64; break;
case 3: green += 160; red += 32; blue += 64; break;
case 4: green += 32; red += 4; blue += 16; break;
}
// put the colors back into the ARGB format
rgbData[i] = (alpha << 24) + (red << 16) + (green << 8) + blue;
}
return image.createRGBImage(rgbData, image.getWidth(), image.getHeight(), true);
}

You can also cache image.getWidth() and image.getHeight():

int width = image.getWidth();
int height = image.getHeight();
92 page views in the last 30 days.
×