package com.lovo.service;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.image.codec.jpeg.*;
public class CheckCodeService extends BaseService{
@Override
public String press() {
// 设置内容类型为图片
response.setContentType("image/jpeg");
//设置客户端不加图片缓存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
//创建一个内存图片
BufferedImage img = new BufferedImage(100,20,
BufferedImage.TYPE_INT_RGB);
//获得画笔
Graphics g = img.getGraphics();
//创建StringBuffer对象
StringBuffer sb = new StringBuffer();
for(int i=0;i<4;i++){
//获得0-10的随机整数
int temp = (int)(Math.random()*10);
sb.append(temp+" ");
}
HttpSession session = request.getSession();
//去掉字符串
session.setAttribute("check", sb.toString().replaceAll(" ", ""));
//设置画笔颜色
g.setColor(new Color(167,178,23));
//绘制矩形的背景
g.fillRect(0,0,200,30);
//设置字体颜色
g.setColor(new Color(0,0,0));
//向画布绘制字符串
g.drawString(sb.toString(),20,15);
//得到输出字节流
ServletOutputStream out ;
try {
out = response.getOutputStream();
// 发送图片数据
JPEGImageEncoder jpg =JPEGCodec.createJPEGEncoder(out);
jpg.encode(img);
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return null;
}
}