简体   繁体   English

将图形在Jpanel上保存为图像

[英]Save drawing on Jpanel as image

I am developing a drawing program using java socket. 我正在使用Java套接字开发绘图程序。 Multiple users can draw and save it as jpeg. 多个用户可以绘制并将其另存为jpeg。 Currently my save image function only save a blank canvas. 目前,我的保存图像功能仅保存空白画布。 It cannot save the co-ordinates drawn. 它无法保存绘制的坐标。

I am sharing part of my code below. 我在下面共享我的代码的一部分。 =) =)

I did not use paint or paintComponent for my Canvas class because of the use java socket i am experiencing sending coordinate errors. 我没有为Canvas类使用paint或paintComponent,因为使用Java套接字时遇到发送坐标错误。 Instead i am using massDraw(). 相反,我正在使用massDraw()。

    class Canvas extends JPanel {
    private int x, y;
    private float x2, y2;

    public Canvas() {
        super();
        this.setBackground(Color.white);
    }

    public void massDraw(int px, int py, int x, int y, int red, int green,
            int blue, int size) {
        Graphics g = canvas.getGraphics();
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHints(myBrush);

        g2d.setStroke(new BasicStroke(size, BasicStroke.CAP_ROUND,
                BasicStroke.JOIN_BEVEL));
        g2d.setColor(new Color(red, green, blue));
        g.drawLine(px, py, x, y);

    }


}// end Canvas class

SaveJpegOP class SaveJpegOP类

class saveJpegOP implements ActionListener {

    public void actionPerformed(ActionEvent e) {
        // Ask for file name
        String str = JOptionPane
                .showInputDialog(null, "Enter File Name : ");
        // save as jpeg
           BufferedImage bufImage = new BufferedImage(canvas.getSize().width, canvas.getSize().height,BufferedImage.TYPE_INT_RGB);  
           canvas.paint(bufImage.createGraphics());  



        try {
            ImageIO.write(bufImage, "jpg", new File(str + ".jpg"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

Blank canvas is saved because massDraw() is never called, especially it's not called when you invoke canvas.paint(bufImage.createGraphics()) in saveJpegOP . 保存空白画布是因为从不调用massDraw() ,尤其是在saveJpegOP调用canvas.paint(bufImage.createGraphics())时不会调用saveJpegOP

paint() basically redraws entire component and since you decided not to override it (or paintComponent() ), drawMass() is never called and empty canvas is painted. paint()基本上重绘了整个组件,并且由于您决定不重写它(或paintComponent() ), drawMass()从不调用drawMass()drawMass()绘制空白画布。

So you need to override paintComponent() and call massDraw() with appropriate parameters. 因此,您需要重写paintComponent()并使用适当的参数调用massDraw() The parameter values can be, for instance, earlier set as properties in the Canvas class. 例如,可以将参数值更早地设置为Canvas类中的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM