Link to home
Start Free TrialLog in
Avatar of dleslie
dleslie

asked on

Save Graphics2D object to file?

I have a Graphics2D object, and I know nothing about it beyond what information I can gather via the methods available to Graphics2D. How do I save this to file? I have been playing around with JIMI, but I have no idea how to convert it to the necessary ImageProducer class... If that's even possible. Any compressed image type is acceptable, jpeg, png, etc, I don't care. I just need this Graphics2D object dumped to file.

I need an answer ASAP - hence the high points.

Thanks,
-Dan
Avatar of bobbit31
bobbit31
Flag of United States of America image

try something like this:

// Create an image buffer in
//which to paint on.
BufferedImage outImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

// tx is your AffineTransform, apply it to image
Graphics2D g2d = outImage.createGraphics();
g2d.drawImage(<your original image>, tx, null);
g2d.dispose();

// JPEG-encode the image
//and write to file.
OutputStream os = new FileOutputStream(<name of new file>);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(outImage);
os.close();
Avatar of dleslie
dleslie

ASKER

I can't do that since all I have is a Graphics2D object provided by an external class I have no access to, unless I could somehow convert this Graphics2D object to a buffered image, this method is impossible.

Thanks,
-Dan
Avatar of Mick Barry
What you are requesting does not make sense.
The Graphics2D class is merely a context for performing drawing operations. It does not contain any details about the drawing operations performed by it.
Sounds like instead what you need to do is pass your own Graphics2D object (created as bobbit31 described above) to your external class to paint to.
Avatar of dleslie

ASKER

An external class has already painted to the Graphics2D object, and has passed it along to me to dump it to file. As is painfully obvious, I'm new to this segment of Java, so please bear with me.

Thanks,
-Dan
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
To do what you want, you need to do the reverse and pass a Graphics object to be painted to.
Avatar of dleslie

ASKER

I thought so...

Thanks for the help,
-Dan
No worries.

http://www.objects.com.au
Brainbench MVP for Java 1
http://www.brainbench.com