dcsimg
How do I convert an painted object to an image?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   kalyan_teki
Posted On:   Wednesday, August 13, 2003 11:23 AM


How do I convert a shape(painted using swings) into
a .gif or .jpeg image?

Re: How do I convert an painted object to an image?

Posted By:   Bahman_Barzideh  
Posted On:   Wednesday, August 13, 2003 07:32 PM

The following is crude (but complete) program that does what you are
after. Hope this it is helpful.

import java.io.File;
import java.io.FileOutputStream;

import java.util.Iterator;

import java.awt.Color;
import java.awt.Image;
import java.awt.Graphics;

import java.awt.image.BufferedImage;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;

import javax.imageio.stream.FileImageOutputStream;

public class Test {

private static BufferedImage createImage_ () {

BufferedImage image = new BufferedImage (240, 240, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics ();
graphics.setColor (Color.yellow);
graphics.fillRect (1, 1, 100, 100);
graphics.fillRect (100,100, 100, 100);

graphics.setColor (Color.red);
graphics.drawRect (50, 50, 100, 100);

return (image);

}

private static ImageWriter getImageWriter_ (String type) {

Iterator iter = ImageIO.getImageWritersByFormatName (type);
if (iter.hasNext () == false)
return (null);

return ((ImageWriter) iter.next ());

}

public static void main (String args []) {

ImageWriter writer = getImageWriter_ ("jpeg");
if (writer == null) {
System.out.println ("could not get a writer");
System.exit (0);
}

BufferedImage image = createImage_ ();
IIOImage iioImage = new IIOImage (image, null, null);

try {
FileImageOutputStream os = new FileImageOutputStream (new File ("output.jpg"));
writer.setOutput (os);
writer.write (iioImage);
os.close ();
System.exit (0);
}
catch (Exception ex) {
ex.printStackTrace ();
}
}

}
About | Sitemap | Contact