Domanda

Devo creare un BufferedImage rettangolare con un colore di sfondo specificato, disegnare un motivo sullo sfondo e salvarlo su file. Non so come creare lo sfondo.

Sto usando un ciclo nidificato:

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

Ma è molto lento quando l'immagine è grande.

Come impostare il colore in modo più efficiente?

È stato utile?

Soluzione

Ottieni l'oggetto grafico per l'immagine, imposta il colore corrente sul colore desiderato, quindi chiama fillRect (0,0, larghezza, altezza) .

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

Altri suggerimenti

Probabilmente qualcosa del tipo:

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

Usa questo:

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

Per chi vuole anche salvare l'immagine creata in un file, ho usato le risposte precedenti e ho aggiunto la parte di salvataggio del file:

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

Puoi anche salvare l'immagine in altri formati come bmp, jpg, ecc ...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top