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 Demo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { int WIDTH = 100; int HIGHT = 30; //在内在中创建一幅图片 BufferedImage image = new BufferedImage(WIDTH,HIGHT,BufferedImage.TYPE_INT_RGB); //取得一个画笔 Graphics g = image.getGraphics(); //设置字符串格式 g.setFont(new Font("黑体",Font.BOLD,24)); //画干扰线 for(int i=0;i<7;i++){ Random r = new Random(); int x1 = r.nextInt(WIDTH); int x2 = r.nextInt(WIDTH); int y1 = r.nextInt(HIGHT); int y2 = r.nextInt(HIGHT); Color color = new Color( (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128); g.setColor(color); g.drawLine(x1, y1, x2, y2); } //得到一个随机颜色 Color color = new Color( (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128); g.setColor(color); //画字符串 g.drawString(getVaule(), WIDTH/5, 2*HIGHT/3);
//blog.sina.com.cn/flyzhouw Color color1 = new Color( (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128); g.setColor(color1); g.drawString(getChar(), WIDTH/3, 2*HIGHT/3); Color color2 = new Color( (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128); g.setColor(color2); g.drawString(getVaule(), WIDTH/2, 2*HIGHT/3); Color color3 = new Color( (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128, (new Double(Math.random() * 128)).intValue() + 128); g.setColor(color3); g.drawString(getChar(), 2*WIDTH/3, 2*HIGHT/3); //将内存中的图片,输出浏览器 ImageIO.write(image, "JPG", response.getOutputStream()); } private String getVaule() { Random r = new Random(); int num = r.nextInt(10); return num + ""; } private String getChar() { Random random =new Random(); int r = 0 ; while(true) { r = random.nextInt(57) + 65; if(r>90&&r<97||r==0)continue; break; } char a = (char)r; return a + ""; }
}