将Jpanel上的图形另存为图像



我正在使用java套接字开发一个绘图程序。多个用户可以绘制并保存为jpeg。目前我的保存图像功能只保存一个空白画布。它无法保存绘制的坐标。

我在下面分享我的部分代码。=)

我的Canvas类没有使用paint或paintComponent,因为我在发送坐标错误时遇到了使用java套接字的问题。相反,我使用的是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 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();
}
}
}

保存空白画布是因为massDraw()从未被调用,尤其是当您在saveJpegOP中调用canvas.paint(bufImage.createGraphics())时,它不会被调用。

paint()基本上是重绘整个组件,并且由于您决定不覆盖它(或paintComponent()),因此永远不会调用drawMass(),并且绘制空画布。

因此,您需要覆盖paintComponent()并使用适当的参数调用massDraw()。例如,参数值可以在Canvas类中较早地设置为属性。

最新更新