// The JDK doesn't seem to dither the image correctly if I go
// below 8bits per pixel. So I dither to an 8bit pallete
// image that only has nCubes colors. Then I copy the data to
// a lower bit depth image that I return.
IndexColorModel icm=new IndexColorModel(8,nCubes,r,g,b);
indexed =new BufferedImage
(w, h, BufferedImage.TYPE_BYTE_INDEXED, icm);
Graphics2D g2d=indexed.createGraphics();
g2d.setRenderingHint
(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_ENABLE);
g2d.drawImage(bi, 0, 0, null);
g2d.dispose();
int bits;
for (bits=1; bits <=8; bits++) {
if ((1<<bits) >= nCubes) break;
}
// System.out.println("Bits: " + bits + " Cubes: " + nCubes);
if (bits > 4)
// 8 bit image we are done...
return indexed;
// Create our low bit depth image...
if (bits ==3) bits = 4;
ColorModel cm=new IndexColorModel(bits,nCubes,r,g,b);
SampleModel sm = new MultiPixelPackedSampleModel
(DataBuffer.TYPE_BYTE, w, h, bits);
WritableRaster ras = Raster.createWritableRaster
(sm, new Point(0,0));