}
IndexColorModel colorModel = new IndexColorModel(8, r.length, r, g, b, a);
// create a image with the reduced colors
BufferedImage reducedImage = new BufferedImage(width, height,
BufferedImage.TYPE_BYTE_INDEXED, colorModel);
// manipulate raster directly for best performance & color match
WritableRaster raster = reducedImage.getRaster();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
// add 1 as transparent is first
int value = transparent[x][y] ? 0 : (pixels[x][y] + 1);
raster.setSample(x, y, 0, value);