tags:

views:

72

answers:

3

I would like to create a gif image of a filled red circle on a green background. What is the easiest way to do it in Java?

+1  A: 

Create a BufferedImage and then write it to a file with ImageIO.write(image, "gif", fileName).

Roman
+1  A: 

If you already have an image file or image URL, then you can use Toolkit to get an Image:

Image img = Toolkit.getDefaultToolkit().createImage(filename);

If you need to construct a new image raster and paint into the image, then you can use BufferedImage. You can paint onto a BufferedImage, by calling its createGraphics function and painting on the graphics object. To save the BufferedImage into a GIF, you can use the ImageIO class to write out the image.

Michael Aaron Safyan
Using Toolkit for reading images is an obsolete way.
Roman
@Roman, what is the new way?
Michael Aaron Safyan
A: 

The best way is to generate a BufferedImage:

BufferedImage img = new BufferedImage(int width, int height, int imageType) 
// you can find the Types variables in the api

Then, generated the Graphics2D of this image, this object allows you to set a background and to draw shapes:

Graphics2D g = img.createGraphics();
g.setBackground(Color color) ; //Find how to built this object look at the java api
g.draw(Shape s);
g.dispose(); //don't forget it!!!

To built the image:

File file = new File(dir, name);
try{
  ImageIO.write(img, "gif", file);
}catch(IOException e){
  e.printStackTrace();
}
anvazp