首页 > 解决方案 > 尝试在 Swing 中保存图形图像会导致图像被截断,每隔几张图像

问题描述

我正在尝试使用BufferedImage,Graphics2D和保存图形图像JAIHelper,但由于某种原因,每 4-5 张图片中的一张在缺少数据的情况下保存(图像被切断)。首先我得到了一个NullPointerexception,然后我稍微改变了它,现在它变得更好了,但仍然每 4-5 个图像我都会得到一个截断的图像。

这是我的代码:

@Override
public void saveGraph(State state, String fileName, IndexTable xVals, IndexTable yVals) {
    try {
        graphPanel.updateGraph(xVals, yVals);
        JPanel panel = graphPanel.getGraph();
        JFrame frame = new JFrame();
        try {
            frame.add(panel);
            frame.setSize(500, 350);
            frame.setVisible(true);
            BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = image.createGraphics();
            try {
                panel.paint(graphics);
                JAIHelper.saveImage(PlanarImage.wrapRenderedImage(image), fileName);
            } finally {
                if (graphics != null) {
                    graphics.dispose();
                }
            }
        } finally {
            frame.dispose();
        }       
    } catch (Exception e) {
        e.printStackTrace();
    }
}

标签: javaimageswinggraphics

解决方案


推荐阅读