Short answer: Yes, you can
A Graphics2D object that has been created on a buffered Image knows the image but isn't willing to hand it back to you. If you don't mind using reflection, you can steal it back (reflection). The following code demonstrates the approach:
public class Graphics2DReflector {
public static void main(String[] args) {
// prepare the Graphics2D - note, we don't keep a ref to the image!
final Graphics2D g2d =
new BufferedImage(100,100,BufferedImage.TYPE_INT_RGB).createGraphics();
g2d.drawString("Reflected", 10, 50);
JFrame frame = new JFrame("Reflected Image");
// one Panel to show the image only known by g2d
frame.getContentPane().add(new Panel() {
@Overwrite
public void paint(Graphics g) {
try {
SurfaceData data = ((SunGraphics2D) g2d).surfaceData;
Field bufImg = BufImgSurfaceData.class.getDeclaredField("bufImg");
bufImg.setAccessible(true);
BufferedImage image = (BufferedImage) bufImg.get(data);
g.drawImage(image,0,0,null);
} catch (Exception oops) {
oops.printStackTrace();
}
}
});
frame.setSize(200,200);
frame.setVisible();
}
}
Note: this depends on some Sun/Oracle classes and may not work with all Java VMs. At least it shows an approach and you may have to inspect the actual classes to get the fields.