Pregunta

Necesito crear una BufferedImage rectangular con un color de fondo especificado, dibujar un patrón en el fondo y guardarlo en el archivo. No sé cómo crear el fondo.

Estoy usando un bucle anidado:

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

Pero es muy lento cuando la imagen es grande.

¿Cómo configurar el color de una manera más eficiente?

¿Fue útil?

Solución

Obtenga el objeto gráfico para la imagen, establezca la pintura actual en el color deseado, luego llame a fillRect (0,0, ancho, alto) .

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

Otros consejos

Probablemente algo como:

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

Use esto:

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

ig2.setBackground(Color.WHITE);
ig2.clearRect(0, 0, width, height);
BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_ARGB);
int[]data=((DataBufferInt) image.getRaster().getDataBuffer()).getData();
Arrays.fill(data,color.getRGB());

Para aquellos que también desean guardar la imagen creada en un archivo, he usado respuestas anteriores y he agregado la parte para guardar el archivo:

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

También puede guardar la imagen en otros formatos como bmp, jpg, etc. ...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top