CreateImage source code:
import
javax.imageio.*;
import
javax.imageio.stream.*;
import
java.io.*;
import
java.awt.*;
import
java.awt.geom.*;
import
java.awt.image.*;
import
java.awt.color.*;
import
javax.swing.*;
import
java.util.*;
class
ImageShow extends Canvas{
public void paint(Graphics g){
1 BufferedImage
bi=(BufferedImage)createImage(400,400);
2 Graphics2D
g2d=(Graphics2D)bi.createGraphics();
3 g2d.setPaint(new
Color(0,0,255));
4 g2d.fill(new
Ellipse2D.Double(125,100,150,200));
g2d.setPaint(new
Color(0,100,10));
g2d.fill(new
Ellipse2D.Double(120,50,50,100));
g2d.setPaint(new
Color(0,100,10));
g2d.fill(new
Ellipse2D.Double(220,50,50,100));
Date dat=new Date();
g2d.setPaint(new
Color(255,10,10));
g2d.drawString(dat.toString(),120,350);
5 g.drawImage(bi,0,0,400,400,null);
g.setColor(Color.WHITE);
g.drawString("myimage.jpg
file of this image is created in the current folder.",300,300);
try{
6 ImageIO.write(bi,"jpg",new
File("myimage.gif"));
}catch(IOException e){}
}
}
class
ShowProgram extends JFrame{
ShowProgram(){
//Set
program title
setTitle("Create
Image");
//Create
ImageShow object that is a drawing area
ImageShow
is=new ImageShow();
//Set
background color of the drawing area
is.setBackground(Color.BLACK);
//Add the
drawing area to the center of the program window
add(is,
BorderLayout.CENTER);
//Let the
program close when the close button is clicked.
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Maximize
the program window
setExtendedState(this.getExtendedState()
| this.MAXIMIZED_BOTH);
//Make use
the program window visible
setVisible(true);
}
}
public class
CreateImage{
public static void main(String[]
args) {
new ShowProgram();
}
}
Code Explanation
1 The BuffereedImage object must be created to store the image data. You will use the createImage(width,height) of the container object to create the empty BufferedImage object.
2 To draw things on the BufferedImage object, the Graphics2D object must be obtained by calling the createGraphics method of the BufferedImage object.
3 Set the color of the pen.
4 Create and fill the ellipse shape.
5 Display the image on the screen.
6 Create the image file called myimage.jpg in the current working folder by calling the write(BufferedImage, Type, File) method of the ImageIO class.
No comments:
Post a Comment