按钮“保存”保存空白画布

时间:2014-05-28 12:34:41

标签: java canvas applet bufferedimage

以下是我简单图形编辑器代码的一部分。这应该保存我绘制的图像,但它保存了一个空白画布。我做错了什么?

BufferedImage bi = new BufferedImage(center.getWidth(), center.getHeight(), BufferedImage.TYPE_INT_RGB);  
Graphics2D g2 = bi.createGraphics();
center.printAll(g2);  
g2.dispose();
JFileChooser jfc = new JFileChooser();
int ret = jfc.showDialog(null, "Save file");                
if (ret == JFileChooser.APPROVE_OPTION) {
    File outputFile = jfc.getSelectedFile();
    ImageIO.write(bi, "BMP", outputFile);

1 个答案:

答案 0 :(得分:0)

绘制组件时

双缓冲必须暂时禁用不可显示的组件(不属于可见框架的那些)首先需要 layouted (否则它们的大小为0x0)。

以下代码将任何组件绘制成BufferedImage:

public static BufferedImage paint(Component component) {
    RepaintManager repaintManager = RepaintManager.currentManager(component);
    boolean wasDoubleBuffered = repaintManager.isDoubleBufferingEnabled();
    try {
        repaintManager.setDoubleBufferingEnabled(false);
        Dimension size = component.getSize();
        if (!component.isDisplayable()) {
            if (size.width <= 0 || size.height <= 0) {
                size = component.getPreferredSize();
                component.setSize(component.getPreferredSize());
            }
            synchronized (component.getTreeLock()) {
                layoutComponent(component);
            }
        }

        BufferedImage image = createCompatibleImage(size.width, size.height);
        Graphics2D g2 = image.createGraphics();
        component.paint(g2);
        g2.dispose();
        return image;
    }
    finally {
        repaintManager.setDoubleBufferingEnabled(wasDoubleBuffered);
    }
}

private static void layoutComponent(Component component) {
    component.doLayout();
    if (component instanceof Container) {
        for (Component child : ((Container) component).getComponents()) {
            layoutComponent(child);
        }
    }
}

public static GraphicsConfiguration getGraphicsConfiguration() {
    return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
}

public static BufferedImage createCompatibleImage(int width, int height) {
    return getGraphicsConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}