如何使用ImageIO保存使用Graphics创建的Java图像

时间:2019-04-09 17:06:34

标签: java javax.imageio

我正在使用图形库创建图像,并尝试使用BufferedImage和ImageIO保存创建的图像。运行后,我的图像弹出,但保存的图像只是黑色。

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!");
    }

}

我希望保存到mickey.png的图像与我之前在mickey方法中绘制的图像相同。

1 个答案:

答案 0 :(得分:2)

您需要执行以下操作:

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

重新排列代码以在mickey()和paint()外部进行保存。