I’m trying to code a program, that reads an Image into a BufferedImage, paint it on the JFrame, paint circles in it, and writes it to a File.
The following code will do all of it except the content of the saved file. The saved image only contains the untouched BufferedImage. No Circles 😉 I already treid to figure it out by changing and adding some code, but it didn’t help a lot.
public class PaintImage extends Component {
BufferedImage img;
private int pngWidth, pngHeight;
public int getPngWidth() {
return pngWidth;
}
public int getPngHeight() {
return pngHeight;
}
public void paint(Graphics g) {
super.paint(g);
//g = img.createGraphics();
g.drawImage(img, 0, 0, 809, 1080, null);
g.drawOval(33, 33, 444, 444);
}
public PaintImage() {
try {
img = ImageIO.read(new File("C:\\karte_vorlage.png"));
pngWidth = img.getWidth();
pngHeight = img.getHeight();
} catch (IOException e) {
}
}
public void writeImage () {
try {
img.getGraphics();
ImageIO.write(img, "png", new File("C:\\save.png"));
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
Uncommenting g = img.createGraphics(); causes a disorted image.
Please help me. thank you all in advance.
edit:
1. The method paint(Graphics g) is called twice. In case of minimizing it will be called twice again.
You could just simple paint the component directly to the
BufferedImageYou may want to play around with the width & height to better meet your requirements though
UPDATED
Keep thinking about this.
Another idea would be to create some kind of “paint manager” or “paintable” interface, that given a
Graphicscontent could paint it self (obviously you’d like to know some more info, likewidth&height)This would mean that it wouldn’t matter where it was painted.
The other thing is you might like to provide hints back to the renderer about how the
paintablewould like to be painted (something like preferred size)Just an idea