Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

J2ME Customizing Game Sprites Color

From Wiki
Jump to: navigation, search

This article shows how you can change the colours of sprite images programmatically. This approach can be used to allow customise game characters, for example to change the colors of hairs, eyes, shirt, etc.

J2me custom colors.png

There are two options for allowing customised sprite colours:

  • Include a different image for each color of each different part of the sprite (e.g. arms, legs, etc.)
  • Replace colors by code

The second options will save you the effort to create these multiple images, and will strip down your JAR size. Also, it will allow you to support a lot more colors.

You can see a simple midlet showing the following snipped of code in action on this page.

Here is the code that takes your input image, the color to be replaced and the new color, and returns a new image.

Some notes on this code:

  • The Image.getRGB method() returns colors as effectively represented by phone, so they can be different from the original colors of your image. This is the reason why we use the getDeviceColor to get the effective color to be replaced, since on different phones it can be represented differently.
  • The limit of this approach is that if 2 different colors of your image map to the same color (because the phone has a limited range of available colors), both of them will be replaced with the new color.
  • A simple optimization of this code will be to store the rbg[] data in a variable, to reuse it for all the color replacement operations
import javax.microedition.lcdui.Image;
public class ColorChanger
public static Image changeColor(Image source, int fromColor, int toColor)
int imageWidth = source.getWidth();
int imageHeight = source.getHeight();
int[] rgb = new int[imageWidth * imageHeight];
int deviceColor = getDeviceColor(fromColor);
source.getRGB(rgb, 0, imageWidth, 0, 0, imageWidth, imageHeight);
for(int i = 0; i < rgb.length; i++)
if(rgb[i] == deviceColor)
rgb[i] = toColor | (0xFF<<24);
return Image.createRGBImage(rgb, imageWidth, imageHeight, true);
static int getDeviceColor(int color)
Image fake = Image.createRGBImage(new int[]{color}, 1, 1, false);
int[] rgb = new int[1];
fake.getRGB(rgb, 0, 1, 0, 0, 1, 1);
return rgb[0];
Article Metadata
Tested with
Devices(s): Nokia 7373, Nokia N82
Platform(s): Series 40, Symbian
Series 40
S60 3rd Edition FP2
Created: jappit (14 Apr 2008)
Updated: tiviinik (17 Jan 2012)
Last edited: hamishwillee (30 Jul 2013)
This page was last modified on 30 July 2013, at 08:03.
43 page views in the last 30 days.