星期五, 五月 07, 2004

使用Servlet动态生成文本图象.

/**
*使用方法在HTML使用<img src="http://servletname"
*/
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Color;
import java.awt.Font;
import javax.imageio.ImageIO;
import java.awt.font.*;
import java.awt.geom.*;

public class DisplayPicture extends HttpServlet {
private static final String text="不存在图片";

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
OutputStream sos=response.getOutputStream();
String storedirectory=getServletConfig().getInitParameter("FileDirectory");
if(storedirectory==null || storedirectory=="")
{
DisplayTextPicture("web.xml??");
return;
}

File pf=new File(storedirectory+"\\2.jpg");
FileInputStream fis;
if(!pf.exists())
{
response.setContentType("image/png");
ImageIO.write(DisplayTextPicture(text+"\n"+storedirectory),"png",sos);
sos.close();
return;
}
//set contenttype
response.setContentType("image/"+getFileType(pf));
fis = new FileInputStream(pf);
byte[] input=new byte[512];
int count=0;
while(fis.read(input) !=-1)
{
sos.write(input);
}
fis.close();
sos.flush();
sos.close();
}

public String getFileType(File pf)
{
String type="gif";
if(pf.getName().toLowerCase().endsWith(".png"))
{
type = "png";
}
if(pf.getName().toLowerCase().endsWith(".gif"))
{
type = "gif";
}
if(pf.getName().toLowerCase().endsWith(".jpg"))
{
type = "jpg";
}
if(pf.getName().toLowerCase().endsWith(".bmp"))
{
type = "bmp";
}
return type;
}
/**
*DisplayTextPicture支持多行显示图片,分割符号为\n
**/
public BufferedImage DisplayTextPicture(String willtext)
{
int width=48;
int height=48;
float size=20.0f;
int StringH=20;
BufferedImage buffer =new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics2D g2=buffer.createGraphics();
Font font = new Font("serif", Font.BOLD, StringH);
font = font.deriveFont(size);
FontRenderContext fc = g2.getFontRenderContext();
Rectangle2D bounds = font.getStringBounds(willtext,fc);
width = (int) bounds.getWidth();
height = (int) bounds.getHeight()*2;

buffer =new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
g2=buffer.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(font);
g2.setColor(Color.white);
g2.fillRect(0,0,width,height);
g2.setColor(Color.blue);
String[] tem=willtext.split("\n");
for(int i=0;i<tem.length;i++)
g2.drawString(tem[i],0,(int)-bounds.getY()+i*StringH);
return buffer;
}
}