Home Java Example Java Swing Graphics2D Generate Image Files

Related Tutorials


 
 

Share on Google+Share on Google+

Generate Image Files

Advertisement
This section illustrates you how to generate image files. For this, we have used the class ImageIO which provides methods for locating ImageReaders and ImageWriters.

Generate Image Files

     

This section illustrates you how to generate image files. For this, we have used the class ImageIO which provides methods for locating ImageReaders and ImageWriters.  

The method createGraphics() creates a Graphics2D and draw into the BufferedImage. To render the specified font on a particular screen, the class FontMetrics is used. The method getFontMetrics() get the font metrics of current font. The method getAscent() provides the font ascent of the font. The method stringWidth(text) returns the total width to show the specified string in the specified font.

The method writes() writes an image using ImageWriter in the file.

Here is the code of GenerateImageType.java

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.ImageIO;

public class GenerateImageType {
  static public void main(String args[]) throws Exception {
  int width = 200, height = 180;
  BufferedImage bufferedImage = new BufferedImage(width, height,
   BufferedImage.TYPE_INT_ARGB);

  Graphics2D g2d = bufferedImage.createGraphics();
  
  Font font = new Font("Arial", Font.BOLD, 24);
  g2d.setFont(font);
  String text = "Welcome!";
  FontMetrics fontMetrics = g2d.getFontMetrics();
  int stringWidth = fontMetrics.stringWidth(text);
  int stringHeight = fontMetrics.getAscent();
  g2d.setPaint(Color.black);
  g2d.drawString(text, (width - stringWidth) / 2, height / 
  stringHeight / 
4);
  
  ImageIO.write(bufferedImage, "gif"new File("C:\\image.GIF"));
  ImageIO.write(bufferedImage, "JPEG"new File("C:\\image.JPG"));
  ImageIO.write(bufferedImage, "PNG"new File("C:\\image.PNG"));
  ImageIO.write(bufferedImage, "BMP"new File("C:\\image.BMP"));
  ImageIO.write(bufferedImage, "TIF"new File("C:\\image.TIF"));
 }
}

After compilation, when you the run the program, the image files are saved in the specified location. The image file contains the following image:

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: October 15, 2008

Related Tutorials

Discuss: Generate Image Files   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com