1 /** 2 有许多的动态生成的图像都是使用servlet完成的,而且代码较多,这里的这段代码是用命令生成图像文件。 3 创建一个BufferedImage对象,将你的“画”放到这个缓冲里, 4 打开一个文件,将图像流编码后输入这个文件,这样就有一个jpg文件出现了。 5 */
1 import java.awt.Color; 2 import java.awt.Graphics; 3 import java.awt.image.BufferedImage; 4 import java.io.BufferedOutputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.util.Vector; 9 import com.sun.image.codec.jpeg.*; 10 11 public class treGraphics { 12 BufferedImage image; 13 14 // 创建jpg文件到指定路径下 15 public void createJpg(String path) { 16 try{ 17 FileOutputStream fos = new FileOutputStream(path); 18 BufferedOutputStream bos = new BufferedOutputStream(fos); 19 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos); 20 encoder.encode(image); 21 bos.close(); 22 23 }catch(FileNotFoundException fnfe){ 24 System.out.println(fnfe); 25 }catch(IOException ioe){ 26 System.out.println(ioe); 27 } 28 } 29 public static void main(String[] args){ 30 int width=400,height=200; 31 int xLength = 300,yLength = 150; 32 int count =5; 33 Vector data = new Vector(); 34 data.addElement(new Integer(100)); 35 data.addElement(new Integer(120)); 36 data.addElement(new Integer(150)); 37 data.addElement(new Integer(40)); 38 data.addElement(new Integer(5)); 39 treGraphics tg = new treGraphics(); 40 tg.image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); 41 Graphics g = tg.image.getGraphics(); 42 //画坐标 43 g.setColor(Color.white); 44 g.fillRect(0, 0, width, height); 45 g.setColor(Color.blue); 46 g.drawLine(10,height-10,10,height-10-yLength); 47 g.drawLine(10, height-10, 10+xLength, height-10); 48 //连线 49 int yTo; 50 int yFrom = ((Integer)(data.elementAt(0))).intValue(); 51 for(int i=1;i<count;i++){ 52 yTo = ((Integer)(data.elementAt(i))).intValue(); 53 g.drawLine(10+i*xLength/count, height-10, 10+i*xLength/count, height-15); 54 g.drawLine(10+(i-1)*xLength/count, yFrom, 10+i*xLength/count, yTo); 55 yFrom = yTo; 56 } 57 tg.createJpg("D:aaa.jpg"); 58 } 59 }
时间: 2024-11-06 22:18:49