|
本帖最后由 websos 于 2014-3-14 16:31 编辑
package test;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
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 Verification extends HttpServlet {
Random rnd=new Random();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
// 生成数字和字母的验证码
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BufferedImage img = new BufferedImage(80, 24, BufferedImage.TYPE_INT_RGB);
// 得到该图片的绘图对象
Graphics g = img.getGraphics();
Random r = new Random();
int w=0,h=0;
Color c=null;
while(w< img.getWidth()){
int n=rnd.nextInt(img.getWidth()/4);
h=0;
while(h<img.getHeight()){
int m=rnd.nextInt(img.getHeight()/4);
c= new Color(rnd.nextInt(55)+200, rnd.nextInt(55)+200, rnd.nextInt(55)+200);
g.setColor(c);
g.fillRect(w, h, n, m);
h+=m;
}
w+=n;
}
// 向图片中输出数字和字母
StringBuffer sb = new StringBuffer();
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
int index, len = ch.length;
for (int i = 0; i < 4; i++) {
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(200), r.nextInt(200), r.nextInt
(55)+200));
g.setFont(new Font("新宋体", Font.BOLD|Font.PLAIN, 22));
// 输出的 字体和大小
g.drawString("" + ch[index], (i * 18)+2 , 18);
//写什么数字,在图片 的什么位置画
sb.append(ch[index]);
}
System.out.println(sb.toString());
request.getSession().setAttribute("piccode", sb.toString());
ImageIO.write(img, "PNG", response.getOutputStream());
}
}
小弟开始工作了哇咔咔,不过第一个项目很大很不利,今天做了个验证码生成,从上到下从左到右的背景颜色全是随机的,这样安全性好些不容易被识别
QQ644556636 希望java大手多多指教
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|