Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set BufferedImage to be a color in Java

I need to create a rectangular BufferedImage with a specified background color, draw some pattern on the background and save it to file. I don't know how to create the background.

I am using a nested loop:

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

But it's very slow when the image is large.

How to set the color in a more efficient way?

like image 828
Lily Avatar asked Sep 06 '25 10:09

Lily


1 Answers

Get the graphics object for the image, set the current paint to the desired colour, then call 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() );
like image 74
Pete Kirkham Avatar answered Sep 08 '25 18:09

Pete Kirkham