好东西介绍,直接用 java 命令行动态生成jpg文件

作者在 2008-09-13 21:47:45 发布以下内容

作者:jeru
email: j...@163.net
日期:2001-2-9 11:09:49
/**
* jeruGraphics v 1.0
*
* 看到一些动态生成图象的例子都是servlet完成的,
* 而且程序很长,觉得不是无论从实用性还是可读性来说都不是太好。
* 这里给了段代码,命令行生成图象文件。这样是不是简单易用些呢?
*
* 创建一个 BufferedImage 对象,将你的“画”放到这个缓冲里,
* 再打开一个文件,将图像流编码后输入这个文件,这样就有一个
* jpg文件出现了,试试吧。。。
*
* Mender :
*   Jeru Liu
* Homepage :
*   http://javaren.126.com
* Email: j...@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);
    }
  }

  public static void main(String[] args) {
    int 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");

  }

默认分类 | 阅读 4101 次
文章评论,共0条
游客请输入验证码
浏览21123次