Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedImage draw white when I say red

Tags:

java

image

It must be a very stupid solution but I'm blind.

I have this code:

BufferedImage bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
bi.getGraphics().setColor(Color.red);
bi.getGraphics().fillRect(300, 350, 100, 50);
ImageIO.write(bi, "jpeg", new File("image.jpg"));

And I get this black 800x600 rectangle and a WHITE rectangle in it. Why is this?

Thanks :)

like image 413
Rubén Avatar asked Apr 30 '11 17:04

Rubén


2 Answers

Each time you call getGraphics() on a BufferedImage you get a new Graphics object, so setting the color on one, doesn't set it on the next one. So cache the graphics object.

BufferedImage bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(Color.red);
g.fillRect(300, 350, 100, 50);
ImageIO.write(bi, "jpeg", new File("/home/dave/image.jpg"));
like image 112
MeBigFatGuy Avatar answered Nov 11 '22 03:11

MeBigFatGuy


For reference, here's an example that might be handy for tinkering with a graphics context.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/** @http://stackoverflow.com/questions/5843426 */
public class RedOrWhite extends JPanel {

    private static final int W = 800;
    private static final int H = 600;

    public RedOrWhite() {
        this.setLayout(new GridLayout());
        this.setPreferredSize(new Dimension(W, H));
        int w = W / 2;
        int h = H / 2;
        int r = w / 5;
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bi.createGraphics();
        g.setColor(Color.gray);
        g.fillRect(0, 0, w, h);
        g.setColor(Color.blue);
        g.fillRect(w / 2 - r, h / 2 - r / 2, 2 * r, r);
        g.dispose();
        this.add(new JLabel(new ImageIcon(bi), JLabel.CENTER));
    }

    private void display() {
        JFrame f = new JFrame("RedOrWhite");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new RedOrWhite().display();
            }
        });
    }
}
like image 25
trashgod Avatar answered Nov 11 '22 03:11

trashgod