有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing保存已使用graphics2d、java绘制的缓冲图像

我正在尝试将已绘制的BuffereImage保存为新文件。我打开文件,使用graphics2d在其上绘制(然后在JFrame中显示图像以确保其正常工作,确实如此),然后将其保存到新文件中

问题是: 保存的文件仅为原始图像。它不包含我在上面绘制的任何新图形

以下是我的代码的简化版本:

public driver() throws IOException {
        try {
            image = ImageIO.read(new File("src/mc_map.png"));
        } catch (IOException e) { e.printStackTrace(); }
        this.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
        image = process(image);
    }

稍后在另一种方法中:

    g.draw(new Line2D.Double(road.start.x, road.start.y, road.end.x, road.end.y));
...
br.close();
        image.createGraphics();
        File map = new File("map.png");
        ImageIO.write(image, "png", map);

相关方法:

private BufferedImage process(BufferedImage old) throws IOException {
        int w = old.getWidth();
        int h = old.getHeight();
        BufferedImage img = new BufferedImage(
            w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        g2d.drawImage(old, 0, 0, null);
        g2d.setPaint(Color.BLUE);
        g2d.drawLine(407, 355, 371, 349);
        readAndDraw(g2d);
        g2d.dispose();
        return img;
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }

    private static void create() throws IOException {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new driver());
        f.pack();
        f.setVisible(true);
    }

共 (2) 个答案

  1. # 1 楼答案

    then display the image in a JFrame to make sure its working

    使用Screen Image获取任何组件的BuffereImage并将该映像保存到文件中

  2. # 2 楼答案

    我最近遇到了一个与您非常相似的问题,因此我的解决方案如下:)

    frame只是指正在绘制的JFrame,宽度和高度指正在保存的图像的大小

        try {
            BufferedImage saving = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics graphics = saving.createGraphics();
            frame.paint(graphics);
            g.dispose(graphics);
            File map = new File("map.png");
            ImageIO.write(saving, "png", map);
        } catch(IOException exc) {
            System.out.println("problem saving");
        }
    

    编辑:如果你的JFrame包含除你想要保存的图像以外的任何内容,我建议在你的JFrame中添加一个JPanel,并在其上绘制。您将以几乎与现在相同的方式进行绘制,但在保存时,您将用JPanel的名称替换代码中的帧