Showing posts with label image create. Show all posts
Showing posts with label image create. Show all posts

Friday, May 15, 2015

Using Java Create An Image And Save To File

package com.pkm;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class Main {
    public static void main(String args[]) throws Exception {
 try {
     int width = 200, height = 200;
     // TYPE_INT_ARGB specifies the image format: 8-bit RGBA packed
     // into integer pixels
     BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
     Graphics2D ig2 = bi.createGraphics();
  
     ig2.setColor(Color.red);
     ig2.fillRect(0, 0, width, height);
  
     ig2.setColor(Color.green);
     ig2.fillOval(0, 0, width, height);
 
     Font font = new Font("TimesRoman", Font.BOLD, 80);
     ig2.setFont(font);
     String message = "PKM";
     FontMetrics fontMetrics = ig2.getFontMetrics();
     int stringWidth = fontMetrics.stringWidth(message);
     int stringHeight = fontMetrics.getAscent();
     ig2.setPaint(Color.black);
   
     ig2.drawString(message, (width - stringWidth) / 2, height / 2 + stringHeight / 4); 
   
     ImageIO.write(bi, "PNG", new File("ImageName.PNG"));   
     ImageIO.write(bi, "JPEG", new File("ImageName.JPG"));   
     ImageIO.write(bi, "gif", new File("ImageName.GIF"));   
     System.out.println("Image Create Done");  
 }  
 catch (Exception ex) {  
     ex.printStackTrace();  
 } 
    }
}

Output