Hopefully it’s just because it’s so late, but for the life of me I can’t figure this out. I start with an 8-bit PNG image. I can create a grayscale version of this image with Java2D like so:
private static final IndexColorModel createGreyscaleModel() {
int SIZE = 256;
byte[] r = new byte[SIZE];
byte[] g = new byte[SIZE];
byte[] b = new byte[SIZE];
for (int i=0; i<SIZE; i++) {
r[i] = g[i] = b[i] = (byte)i;
}
return new IndexColorModel(8, SIZE, r, g, b);
}
private static final BufferedImage createIndexedCopy(Image orig, IndexColorModel cm, int scale) {
int w = orig.getWidth(null);
int h = orig.getHeight(null);
BufferedImage out = new BufferedImage(w*scale, h*scale, BufferedImage.TYPE_BYTE_INDEXED, cm);
Graphics2D g2d = out.createGraphics();
// g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
// g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
// g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
// g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g2d.drawImage(orig, 0, 0, w*scale, h*scale, null);
g2d.dispose();
return out;
}
// ...
BufferedImage grayscaleImage = createIndexedCopy(otherImage, createGreyscaleModel(), 1);
The end result looks like what I’d expect. So next, I thought I’d try to create a “greenscale” version of the image by creating the color model like so:
private static final IndexColorModel createGreenModel() {
int SIZE = 256;
byte[] r = new byte[SIZE];
byte[] g = new byte[SIZE];
byte[] b = new byte[SIZE];
for (int i=0; i<SIZE; i++) {
g[i] = (byte)i;
}
IndexColorModel model = new IndexColorModel(8, SIZE, r, g, b);
return model;
}
But the end result isn’t what I want. It looks as if some kind of interpolation was done, even though the image was never scaled. This happens even when the original image is just a single color. See the example below. The original (blue) image has all pixels a single color, the grayscale version looks good, but the green version doesn’t…
What am I missing?