如何将BufferedImage转换为8位?

时间:2012-06-16 08:56:53

标签: java image image-processing bufferedimage 8-bit

我正在查看ImageConverter类,试图弄清楚如何将BufferedImage转换为8位颜色,但我不知道如何做到这一点。我也在互联网上搜索,我找不到简单的答案,他们都在谈论8位灰度图像。我只是想将图像的颜色转换为8位......没有别的,没有任何调整大小。有谁介意告诉我如何做到这一点。

3 个答案:

答案 0 :(得分:5)

您可以使用官方Sun(现在的Oracle)图像库JAI(Java Advanced Imaging)来实现这一目标。

ColorQuantizerDescriptor显示您可以应用的量化过程的选择。

答案 1 :(得分:3)

文章"Transparent gifs in Java" at G-Man's Uber Software Engineering Blog中的此代码段效果很好:

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's 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 :(得分:2)

您可以使用convert8类中的ConvertUtil方法。

有关详细信息,请查看here