How to convert BufferedImage to 8 bits?

I looked at the ImageConverter class, trying to figure out how to convert BufferedImage to 8-bit color, but I have no idea how to do this. I also searched the Internet, and I could not find a simple answer, they all talked about 8-bit grayscale images. I just want to convert the image colors to 8 bits ... nothing more, nothing to resize. Does anyone not know how to do this.

+8
java image image-processing bufferedimage 8bit
source share
3 answers

This code snippet from the article "Transparent gifs in Java" in the G-Man Uber Software Engineering Blog works well:

public static void main(String[] args) throws Exception { BufferedImage src = convertRGBAToIndexed(ImageIO.read(new File("/src.jpg"))); ImageIO.write(src, "gif", new File("/dest.gif")); } public static BufferedImage convertRGBAToIndexed(BufferedImage src) { BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED); Graphics g = dest.getGraphics(); g.setColor(new Color(231, 20, 189)); // fill with a hideous color and make it transparent g.fillRect(0, 0, dest.getWidth(), dest.getHeight()); dest = makeTransparent(dest, 0, 0); dest.createGraphics().drawImage(src, 0, 0, null); return dest; } public static BufferedImage makeTransparent(BufferedImage image, int x, int y) { ColorModel cm = image.getColorModel(); if (!(cm instanceof IndexColorModel)) return image; // sorry... IndexColorModel icm = (IndexColorModel) cm; WritableRaster raster = image.getRaster(); int pixel = raster.getSample(x, y, 0); // pixel is offset in ICM palette int size = icm.getMapSize(); byte[] reds = new byte[size]; byte[] greens = new byte[size]; byte[] blues = new byte[size]; icm.getReds(reds); icm.getGreens(greens); icm.getBlues(blues); IndexColorModel icm2 = new IndexColorModel(8, size, reds, greens, blues, pixel); return new BufferedImage(icm2, raster, image.isAlphaPremultiplied(), null); } 
+2
source share

You can use JAI (Java Advanced Imaging), the official Sun image library (now Oracle), to do this.

ColorQuantizerDescriptor shows a selection of quantization processes that you can apply.

+4
source share

You can use the convert8 method in the ConvertUtil class.

See here for more details.

+1
source share

All Articles