user1891904
user1891904

Reputation:

Save drawing on Jpanel as image

I am developing a drawing program using java socket. Multiple users can draw and save it as 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. Instead i am using 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

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();
        }

    }

}

Upvotes: 1

Views: 1213

Answers (1)

Adam Dyga
Adam Dyga

Reputation: 8896

Blank canvas is saved because massDraw() is never called, especially it's not called when you invoke canvas.paint(bufImage.createGraphics()) in 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.

So you need to override paintComponent() and call massDraw() with appropriate parameters. The parameter values can be, for instance, earlier set as properties in the Canvas class.

Upvotes: 1

Related Questions