import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//生成随机图片
public class Yanzm01 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置浏览器不能缓存
response.setHeader("expires","-1");
response.setHeader("cache-control","no-cache");
response.setHeader("pragma","no-cache");
//在内存中构造一副图片
BufferedImage image = new BufferedImage(500,25,BufferedImage.TYPE_INT_RGB);
//取得画笔
Graphics g = image.getGraphics();
//设置字体大小和颜色
g.setColor(Color.YELLOW);
g.setFont(new Font("黑体",Font.BOLD,22));
//在图片中显示字符串 1azb
g.drawString(getString(),20,20);
ImageIO.write(image, "jpg", response.getOutputStream());
}
/**产生一个随机数*/
private String getString()
{
//唯一ID号
//UUID.randomUUID().toString();
return UUID.randomUUID().toString();
}
}
/**产生一个4位随机数第一个数字,第二个字母,第三个数字,第四个字母*/
private String getStringfor()
{
String str = "";
String numberAndLetter="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int length = numberAndLetter.length(); //取得全部长度
for(int i=1;i<=4;i++){ //验证码长度
if(i==1 || i==3){//如果1、3、位数字
while(true){
Random random = new Random();
int index = random.nextInt(length);
//substring(int beginIndex, int endIndex)
//返回一个新的字符串,它是此字符串的一个子字符串。该子字符串始于指定索引处的字符,一直到此字符串末尾。
String value = numberAndLetter.substring(index,index+1);
if(value.matches("[0-9]")){ //正则判断
str += value;
break;
}
}
}else if(i==2 || i==4){//如果2、4位大小字母
while(true){
Random random = new Random();
int index = random.nextInt(length);
String value = numberAndLetter.substring(index,index+1);
if(value.matches("[A-Za-z]")){
str += value;
break;
}
}
}
}
return str;
}
原文地址:http://blog.51cto.com/357712148/2104694