27

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?

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Lily
  • 5,872
  • 19
  • 56
  • 75

5 Answers5

67

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() );
Pete Kirkham
  • 48,893
  • 5
  • 92
  • 171
9

Probably something like:

BufferedImage image = new BufferedImage(...);
Graphics2D g2d = image.createGraphics();
g2d.setColor(...);
g2d.fillRect(...);
camickr
  • 321,443
  • 19
  • 166
  • 288
8

Use this:

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

ig2.setBackground(Color.WHITE);
ig2.clearRect(0, 0, width, height);
Aaaaaaaa
  • 2,015
  • 3
  • 22
  • 40
3
BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
int[]data=((DataBufferInt) image.getRaster().getDataBuffer()).getData();
Arrays.fill(data,color.getRGB());
Laurel
  • 5,965
  • 14
  • 31
  • 57
hoford
  • 4,918
  • 2
  • 19
  • 19
  • better to explain more detail of answer – Mostafiz Apr 29 '16 at 00:14
  • I get java.lang.ClassCastException: java.awt.image.DataBufferByte cannot be cast to java.awt.image.DataBufferInt when I try this in Java 8 – Al G Johnston May 02 '20 at 15:32
  • The approach depends on the internal structure of the actual image you are using. BufferedImage can be of many types depending on where the image came from. DataBufferInt as its name implies mans it a backed by an array of int. Corresponding to type BufferedImage.TYPE_INT_ARGB – hoford May 13 '20 at 15:46
3

For who want also to save the created image to a file, I have used previous answers and added the file saving part:

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);

You can also save the image in other formats like bmp, jpg, etc...

Juan Franco
  • 199
  • 1
  • 7