Tammerg
Tammerg

Reputation: 121

How to save a Java image created with Graphics using ImageIO

I am creating an image using the Graphics library, and attempting to save that created image using BufferedImage and ImageIO. After running, my image pops up, but the saved image is just black.

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class drawing extends Canvas {

    public static void main(String[] args) {
        JFrame frame = new JFrame("My Drawing");
        Canvas canvas = new drawing();
        canvas.setSize(400, 400);
        canvas.setBackground(Color.CYAN);
        frame.add(canvas);
        frame.pack();
        frame.setVisible(true);
    }
    public void paint(Graphics g) {
        Rectangle bb = new Rectangle(100, 100, 200, 200);
        g.setColor(Color.yellow);
        try {
            mickey(g, bb);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void boxOval(Graphics g, Rectangle bb) {
        g.fillOval(bb.x, bb.y, bb.width, bb.height);
        g.setColor(Color.blue);
    }
    public void mickey(Graphics g, Rectangle bb) throws IOException {
        boxOval(g, bb);
        int dx = bb.width / 2;
        int dy = bb.height / 2;
        g.setColor(Color.RED);
        Rectangle half = new Rectangle(bb.x, bb.y, dx, dy);
        half.translate(-dx / 2, -dy / 2);
        boxOval(g, half);
        half.translate(dx * 2, 0);
        boxOval(g, half);
        half.translate(dx / 10, 50);
        boxOval(g, half);

        BufferedImage buff = new BufferedImage(dx, dy, BufferedImage.TYPE_INT_RGB);
        File file = new File("mickey.png");
        System.out.println("saving....");
        ImageIO.write(buff, "png", file);
        System.out.println("saved!");
    }

}

I expect that the image saved to mickey.png would be the same as the one I draw earlier in the mickey method.

Upvotes: 0

Views: 1650

Answers (1)

gpasch
gpasch

Reputation: 2672

You need to do this:

    BufferedImage buff = new BufferedImage(dx, dy, BufferedImage.TYPE_INT_RGB);
    this.paint(buff.getGraphics()); // call paint to draw on the image
    File file = new File("mickey.png");
    System.out.println("saving....");
    ImageIO.write(buff, "png", file);
    System.out.println("saved!");

Rearrange your code to do the saving outside mickey() and outside paint().

Upvotes: 2

Related Questions