Here's an attempt to describe a few ways you could work around the problem, based on discussion in the comments:
The problem is that the original image is using an IndexColorModel
(or a color map or "palette" if you like). There is no green color that exactly matches the color you specify, so instead the color model does a lookup to get the "closest" color to the one you specified (you may not agree to this color being the closest match, but it is given the algorithm used).
If you set the color to one matching the colors of the image, you can paint in that color. Try new Color(0.8f, 0.9019608f, 0.6392157f)
or RGB value 0xffcce6a3
for the light green one. Use new Color(0.6392157f, 0.8f, 1f)
or 0xffa3ccff
for the light blue.
If you wonder how I found those values, here's the explanation. Assuming colorModel
is an IndexColorModel
, you can use:
int[] rgbs = new int[colorModel.getMapSize()];
colorModel.getRGBs(rgbs);
...to get the colors in the color map. Choosing one of these colors should always work.
Now, if your "library" (which you haven't disclosed much details about) is using a fixed palette for generating these images, you are good, and can use one of the colors I mentioned, or use the approach described to get the colors, and choose an appropriate one. If not, you need to dynamically find the best color. And if you're really out of luck, there might be no suitable color available at all (ie., your map tile is all ocean, and the only color available is sea blue, it will be impossible to plot a green dot). Then there's really no other way to solve this, than to modify the library.
A completely different approach, could be similar to @camickr's solution, where you temporarily convert the image to true color (BufferedImage.TYPE_INT_RGB
or TYPE_3BYTE_BGR
), paint your changes onto this temporary image, then paint that image back onto the original. The reason why this might work better, is that the composing mechanism will use a dither and a better color lookup algorithm. But you'll still have the same issue related to available colors as described in the previous paragraph.
Here's a code sample, using the warm yellow color, and the output:
Color color = new Color(0.89411765f, 0.5686275f, 0.019607844f);
int argb = color.getRGB();
Graphics2D g = image.createGraphics();
try {
g.setColor(color);
g.fillRect(10, 10, 50, 50);
}
finally {
g.dispose();
}
