在Java中将BufferedImage设置为一种颜色

27

我需要创建一个指定背景颜色的矩形BufferedImage,在背景上绘制一些图案并保存到文件。我不知道如何创建背景。

我正在使用嵌套循环:

BufferedImage b_img = ...
for every row
for every column
setRGB(r,g,b);

然而当图像很大时,速度非常慢。

如何以更高效的方式设置颜色?

5个回答

67

获取图像的 Graphics 对象,将当前 paint 设置为所需的颜色,然后调用 fillRect(0,0,width,height)

BufferedImage b_img = ...
Graphics2D    graphics = b_img.createGraphics();

graphics.setPaint ( new Color ( r, g, b ) );
graphics.fillRect ( 0, 0, b_img.getWidth(), b_img.getHeight() );

不是 setPaint,而是 setColor - Xdg
@Xdg https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html#setPaint(java.awt.Paint) 颜色是一种画笔;但是setColor也可以像其他答案中那样工作。 - Pete Kirkham
对不起,你说得对。我使用的是Graphics而不是Graphics2D。 - Xdg
不要忘记处理你的图形对象。 - Tilman Hausherr

9
可能是这样的东西:
BufferedImage image = new BufferedImage(...);
Graphics2D g2d = image.createGraphics();
g2d.setColor(...);
g2d.fillRect(...);

8

使用以下内容:

BufferedImage bi = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
Graphics2D ig2 = bi.createGraphics();

ig2.setBackground(Color.WHITE);
ig2.clearRect(0, 0, width, height);

3
BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
int[]data=((DataBufferInt) image.getRaster().getDataBuffer()).getData();
Arrays.fill(data,color.getRGB());

最好详细解释答案。 - Mostafiz
我在Java 8中尝试这个时,收到了java.lang.ClassCastException: java.awt.image.DataBufferByte无法转换为java.awt.image.DataBufferInt的错误信息。 - Al G Johnston
方法取决于您正在使用的实际图像的内部结构。 BufferedImage 可以是许多类型,具体取决于图像来自何处。 DataBufferInt 正如其名称所示,它是由 int 数组支持的。对应于 BufferedImage.TYPE_INT_ARGB 类型。 - hoford

3

如果您还希望将创建的图像保存到文件中,我使用了之前的答案并添加了文件保存部分:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

// Create the image
BufferedImage bi = new BufferedImage(80, 40, ColorSpace.TYPE_RGB);
Graphics2D graphics = bi.createGraphics();

// Fill the background with gray color
Color rgb = new Color(50, 50, 50);
graphics.setColor (rgb);
graphics.fillRect ( 0, 0, bi.getWidth(), bi.getHeight());

// Save the file in PNG format
File outFile = new File("output.png");
ImageIO.write(bi, "png", outFile);

您还可以将图像保存为诸如bmp,jpg等其他格式...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接