如何从图形创建图像? [英] How to create an Image from Graph?

查看:113
本文介绍了如何从图形创建图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我一些关于如何从我创建的图形中保存图像(PNG)的建议吗?

Can somebody please give me some advice about how to save an image (PNG) from my created graph?

这是java程序:

public class GraphingData extends JPanel {
    int[] data = {
             110, 535, 0, 459, 380, 199, 212, 722, 332, 836, 149, 10, 656, 465, 100, 173, 277, 381, 685, 988, 89, 585, 381, 779, 378, 769, 265, 10 
    };
    final int PAD = 20;

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        int w = getWidth();
        int h = getHeight();

        .......
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new GraphingData());
        f.setSize(1000,500);
        f.setLocation(200,200);
        f.setVisible(true);
    }
}


推荐答案

到将面板当前显示在屏幕上的大小(尺寸等)存储到文件中只需执行

To store a panel how it currently shown on screen (sizes etc.) to a file just do

BufferedImage bi = new BufferedImage(panel.getSize().width, panel.getSize().height, BufferedImage.TYPE_INT_RGB);
panel.paint(bi.createGraphics());
ImageIO.write(bi, "PNG", new File("path/to/file.png"));

除此之外,不要使用作为参数给出的图形 paintComponent 直接但是在它上面调用 g.create()如果你完成了那个新的实例调用 dispose()就可以了。您不应该更改有关颜色,转换等的图形对象,并使用 create() dispose()你确定是这种情况。

Besides that, do not use the Graphics that is given as parameter to paintComponent directly but call g.create() on it and if you are finished with that new instance call dispose() on it. You are expected to not change the Graphics object that is put in regarding colors, transformations and so on and with the create() and dispose() you make sure this is the case.

这篇关于如何从图形创建图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆