Skip to main content

How to draw a polygon on an image and save the result

2 replies [Last post]
lcmeng
Offline
Joined: 2007-11-26
Points: 0

Yet another question from a newbie.

My previous code can generate a buffered image. Right now, I wanna display the image with Java2D. In addition, I need to draw a polygon on that image based a set of vertices. Then I need to save the image containing the original image and the polygon.

To draw the both, is it like first g.drawImage(), then g.draw(Polygon polygon). If it is correct, then how can I save the result to a new image file? Thank you in advance.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Dmitri Trembovetski

java2d@JAVADESKTOP.ORG wrote:
> Yet another question from a newbie.
>
> My previous code can generate a buffered image. Right now, I wanna display the image with Java2D. In addition, I need to draw a polygon on that image based a set of vertices. Then I need to save the image containing the original image and the polygon.
>
> To draw the both, is it like first g.drawImage(), then g.draw(Polygon polygon). If it is correct, then how can I save the result to a new image file? Thank you in advance.

Take a look at javax.imageio.* package. In particular,
you can do something like this:
javax.imageio.ImageIO.write(image, "png", new File("saved.png"));

Thanks,
Dmitri

> [Message sent by forum member 'lcmeng' (lcmeng)]
>
> http://forums.java.net/jive/thread.jspa?messageID=253140
>
> ===========================================================================
> To unsubscribe, send email to listserv@java.sun.com and include in the body
> of the message "signoff JAVA2D-INTEREST". For general help, send email to
> listserv@java.sun.com and include in the body of the message "help".

===========================================================================
To unsubscribe, send email to listserv@java.sun.com and include in the body
of the message "signoff JAVA2D-INTEREST". For general help, send email to
listserv@java.sun.com and include in the body of the message "help".

lcmeng
Offline
Joined: 2007-11-26
Points: 0

Thank you for your reply.

"If you invoke createGraphics() on the BufferedImage and draw using the returned Graphics2D instance then the graphics will be "burned" into the actual image pixels. When you write this image to a stream the graphics will be included of course as they would then be part of the image data. To read and write we recommend the Java Image I/O Framework javax.imageio for which https://jai-imageio.dev.java.net provides additional plug-ins."

This is the reply of 'bpb' in JAI section. I didn't know that a bufferedImage can 'createGraphics'....and his reply helped me solve the problem.