本文介绍了如何将BufferedImage转换为8位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was looking at the ImageConverter class, trying to figure out how to convert a BufferedImage to 8-bit color, but I have no idea how I would do this. I was also searching around the internet and I could find no simple answer, they were all talking about 8 bit grayscale images. I simply want to convert the colors of an image to 8 bit... nothing else, no resizing no nothing. Does anyone mind telling me how to do this.

推荐答案

文章Java中的透明GIF在 G-Man的优步软件工程博客 效果很好:

This code snippet from the article "Transparent gifs in Java" at G-Man's 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'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);
}

这篇关于如何将BufferedImage转换为8位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 02:22