//生成图片的 Java Bean
//作者:崔冠宇
//日期:2001-08-24
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.*;
import java.awt.*;
public class ChartGraphics {
BufferedImage image;
public void createImage String fileLocation) {
try {
FileOutputStream fos = new FileOutputStream fileLocation);
BufferedOutputStream bos = new BufferedOutputStream fos);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder bos);
encoder.encode image);
bos.close );
} catch Exception e) {
System.out.println e);
}
}
public void graphicsGeneration int h1,int h2,int h3,int h4,int h5) {
final int X=10;
int imageWidth = 300;//图片的宽度
int imageHeight = 300;//图片的高度
int columnWidth=30;//柱的宽度
int columnHeight=200;//柱的最大高度
ChartGraphics chartGraphics = new ChartGraphics );
chartGraphics.image = new BufferedImage imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics graphics = chartGraphics.image.getGraphics );
graphics.setColor Color.white);
graphics.fillRect 0,0,imageWidth,imageHeight);
graphics.setColor Color.red);
graphics.drawRect X+1*columnWidth, columnHeight-h1, columnWidth, h1);
graphics.drawRect X+2*columnWidth, columnHeight-h2, columnWidth, h2);
graphics.drawRect X+3*columnWidth, columnHeight-h3, columnWidth, h3);
graphics.drawRect X+4*columnWidth, columnHeight-h4, columnWidth, h4);
graphics.drawRect X+5*columnWidth, columnHeight-h5, columnWidth, h5);
chartGraphics.createImage "D:\\temp\\chart.jpg");
}
}
解释:createImage String fileLocation)方法用于创建JPG图片,参数fileLocation为文件路径
graphicsGeneration int h1,int h2,int h3,int h4,int h5)方法用于绘出图片的内容,参数h1……h5为每一个长方形的高度
第二步:创建另一个Java Bean从文本文件中读取数据 每一个长方形的高度),在实际应用中数据存储在Oracle数据库中
源程序如下:
//读取Text文件中数据的 Java Bean
//作者:崔冠宇
//日期:2001-08-24
import java.io.*;
public class GetData {
int heightArray[] = new int[5];
public int[] getHightArray ) {
try {
RandomAccessFile randomAccessFile = new RandomAccessFile "d:\\temp\\ColumnHeightArray.txt","r");
for int i=0;i<5;i++)
{
heightArray[i] = Integer.parseInt randomAccessFile.readLine ));
}
}
catch Exception e) {
System.out.println e);
}
return heightArray;
}
}
解释: getHightArray )用于从文本中读取数据,将文本中的String类型转换为int类型,并以数组类型返回。
第三步:创建JSP文件
源程序如下:
<%@ page import="ChartGraphics" %>
<%@ page import="GetData" %>
<jsp:useBean id="cg" class="ChartGraphics"/>
<jsp:useBean id="gd" class="GetData"/>
<%!
int height[]=new int[5];
%>
<%
height=gd.getHightArray );
cg.graphicsGeneration height[0],height[1],height[2],height[3],height[4]);
%>
<html>
<body>
<img src="d:\temp\chart.jpg"></img>
</body>
</html>
|