当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
直接用java命令行动态生成jpg文件
发布时间:2010/7/19 11:00:33 来源:城市学习网 编辑:ziteng
  /**
  * jeruGraphics v 1.0
  *
  * 看到一些动态生成图象的例子都是servlet完成的,
  * 而且程序很长,觉得不是无论从实用性还是可读性来说都不是太好。
  * 这里给了段代码,命令行生成图象文件。这样是不是简单易用些呢?
  *
  * 创建一个 BufferedImage 对象,将你的“画”放到这个缓冲里,
  * 再打开一个文件,将图像流编码后输入这个文件,这样就有一个
  * jpg文件出现了,试试吧。。。
  *
  * Mender :
  * Jeru Liu
  * Homepage :
  * http://javaren.126.com
  * Email: jeru@163.net
  *
  * 这仅仅是一个范例程序,没什么实用,却极具参考价值。
  *
  */
  import java.io.*;
  import java.util.*;
  import com.sun.image.codec.jpeg.*;
  import java.awt.image.*;
  import java.awt.*;
  public class jeruGraphics {
  BufferedImage image;
  // 创建 jpg 文件到指定路径下
  public void createJpg(String path) {
  try {
  FileOutputStream fos = new FileOutputStream(path);
  BufferedOutputStream bos = new BufferedOutputStream(fos);
  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
  encoder.encode(image);
  bos.close();
  } catch(FileNotFoundException fnfe) {
  System.out.println(fnfe);
  } catch(IOException ioe) {
  System.out.println(ioe);
  }
  } [NextPage]   public static void main(String[] args) {
  int width=400, height=200;
  int xLength=300, yLength=150;
  int count=5;
  Vector data=new Vector();
  data.addElement(new Integer(100));
  data.addElement(new Integer(120));
  data.addElement(new Integer(150));
  data.addElement(new Integer(40));
  data.addElement(new Integer(5));
  jeruGraphics jg = new jeruGraphics();
  jg.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  Graphics g = jg.image.getGraphics();
  // 画坐标
  g.setColor(Color.white);
  g.fillRect(0, 0, width, height);
  g.setColor(Color.blue);
  g.drawLine(10,height-10,10,height-10-yLength);
  g.drawLine(10,height-10,10+xLength,height-10);
  // 连线
  int yTo;
  int yFrom = ((Integer)(data.elementAt(0))).intValue();
  for (int i=1; i<count; i++) {
  yTo=((Integer)(data.elementAt(i))).intValue();
  g.drawLine(10+i*xLength/count,height-10,10+i*xLength/count,height-15);
  g.drawLine(10+(i-1)*xLength/count,yFrom,10+i*xLength/count,yTo);
  yFrom=yTo;
  }
  jg.createJpg("d:\\aaa.jpg");
  }
  }
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved