将颜色添加到灰度BufferedImage

时间:2013-06-03 13:43:08

标签: java image rgb bufferedimage

无法找到答案,也许它太基本了。我有一个灰度BufferedImage(基本上是黑白PDF的一部分),我想在图像上画一个红色框。但是,当我这样做并保存图像时,红色框显示为灰色。

如何正确地将颜色添加到灰度BufferedImage

我想我需要将颜色模型(?)从灰度转换为RGB?虽然我不需要将图像的黑白部分转换为彩色 - 也就是说生成的图像可以是黑白的。只要我能在图像上画一条红线而不保存为灰色阴影。

图像文件是GIF。

1 个答案:

答案 0 :(得分:4)

通过使用以下代码,我可以将RED矩形添加到灰度图像。看看这是否适合你。另外,请告诉我们您遇到的错误。

public static void main(String[] args) throws IOException {
BufferedImage old = ImageIO.read(new File("download.gif"));
int w = old.getWidth();
int h = old.getHeight();

BufferedImage img = new BufferedImage(
        w, h, BufferedImage.TYPE_INT_ARGB);

Graphics2D g2d = img.createGraphics();
g2d.drawImage(old, 0, 0, null);
g2d.setColor(Color.red);
g2d.drawRect(10, 10, 100, 100);
g2d.dispose();

    ImageIO.write(img, "gif", new File("out.gif"));  

    }