How do I create an image using Java?

I would like to create a gif of a filled red circle on a green background. What's the easiest way to do this in Java?

+2


a source to share


3 answers


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

.



+1


a source


If you already have an image file or image url, you can use the Toolkit



to get the Image :

<Preview> Image img = Toolkit


... getDefaultToolkit () . createImage (filename);

If you need to create a new bitmap and draw an image, you can use BufferedImage . You can paint on a BufferedImage by calling the createGraphics function and paint on a graphics object. To store BufferedImage to GIF, you can use ImageIO class to write image.

+1


a source


The best way is to create BufferedImage

:

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

      

Then, created by the Graphics2D of this image, this object allows you to set the background and draw the 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 create an image:

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

      

+1


a source







All Articles