2 years ago
#26711
Jakob
How to export (only) canvas as an image
I want to export an image painted on a canvas to a PNG or JPEG file. I found solutions that allow me to export the whole JPanel, but that's not what I want. When I try to export the canvas, the image I get has the right size but is completely black.
Here is my code:
public void exportImage(String imageName) {
BufferedImage image = new BufferedImage(canvas.getWidth(), canvas.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = (Graphics2D) canvas.getGraphics();
paint(graphics);
graphics.dispose();
try {
System.out.println("Exporting image: " + imageName);
FileOutputStream out = new FileOutputStream(imageName);
ImageIO.write(image, "png", out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Edit:
This is my program
And this is the canvas that should be exported
java
image
swing
canvas
bufferedimage
0 Answers
Your Answer