<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <%@page import="java.awt.image.BufferedImage"%> <%@page import="java.awt.*"%> <%@page import="java.io.OutputStream"%> <%@page import="com.sun.image.codec.jpeg.JPEGImageEncoder"%> <%@page import="com.sun.image.codec.jpeg.JPEGCodec"%> <% //设置页面不缓存 response.setHeader("pragma","no-cache"); response.setHeader("cache-control","no-cache"); response.setDateHeader("expires",0); response.setContentType("Image/gif"); %> <% String s=""; int width=80,height=23; char[] code=new char[]{ 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','p','q','r','s','t','u','v','w','x','y','z', '2','3','4','5','6','7','8','9' }; Random random=new Random(); String strCode; for(int i=0;i<4;i++) { strCode=String.valueOf(code[random.nextInt(code.length)]); s=s+strCode; } //把得到的字符保存到session种 session.setAttribute("code",s); //定义图像buffer BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics2D gra=bufferedImage.createGraphics(); //填充背景颜色 gra.setColor(Color.white); gra.fillRect(0,0,width,height); gra.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,20)); //设置字体样式 //画边框 gra.setColor(Color.blue); gra.drawRect(0,0,width-1,height-1); //产生干扰线 int x1=0,y1=0,x2=0,y2=0; for(int i=0;i<30;i++) { x1=random.nextInt(100); y1=random.nextInt(100); x2=random.nextInt(100); y2=random.nextInt(100); gra.setColor(Color.black); gra.drawLine(x1,y1,x1+x2,y1+y2); } //画出每个字符 char c; for(int i=0;i<4;i++) { c=s.charAt(i); gra.setColor(getColor()); gra.drawString(c+"",i*20+4,20); } OutputStream toClient=response.getOutputStream(); JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(toClient); encoder.encode(bufferedImage); toClient.close(); out.clear(); out=pageContext.pushBody(); %> <%! private Color getColor() { Random random=new Random(); int red=0,green=0,blue=0; red=random.nextInt(100); green=random.nextInt(100); blue=random.nextInt(100); return new Color(red,green,blue); } %>