2009-09-17 300 views
15

我需要用指定的背景顏色創建一個長方形BufferedImage,在背景上繪製一些圖案並將其保存到文件中。我不知道如何創建背景。將BufferedImage設置爲Java中的顏色

我使用嵌套的循環:

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

但它的速度很慢,當圖像較大。

如何以更有效的方式設置顏色?

回答

47

獲取圖像的圖形對象,將當前顏料設置爲所需顏色,然後致電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()); 
6

大概是這樣的:

BufferedImage image = new BufferedImage(...); 
Graphics2D g2d = image.createGraphics(); 
g2d.setColor(...); 
g2d.fillRect(...); 
3

使用此:

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()); 
+0

更好的解釋回答的更多細節 – Mostafiz 2016-04-29 00:14:22