您的位置:首页 > 其它

随机生成图片验证码

2017-12-23 17:27 344 查看
在做项目的时候,我们经常也会用到随机数验证码,下面带大家一起实现验证码的绘制实现过程:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* Servlet implementation class codeServlet
*/
@WebServlet("/code")
public class CodeServlet extends HttpServlet {
//1.指定画板的长宽(即:验证码所在位置的大小)
private int width=80;
private int height=30;

private static final long serialVersionUID = 1L;

public CodeServlet() {
super();
// TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//2.准备画板
BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//3.准备画笔
Graphics g=image.getGraphics();
//4.给画笔上色
Random ran=new Random();
g.setColor(new Color(ran.nextInt(255), ran.nextInt(255), ran.nextInt(255)));
//5.给画板设置背景颜色
g.fillRect(0, 0, width, height);
//6.获取随机的字符串
String number=getNumber(4,ran);
//7.将产生的Number存入session中
HttpSession session=request.getSession();
session.setAttribute("number", number);
//8.绘制字符串
//先转换画笔的颜色
g.setColor(new Color(0,0,0));
g.setFont(new Font(null, Font.ITALIC, 24));
g.drawString(number, 5, 25);
//9.绘制干扰线
for (int i = 0; i < 8; i++) {
g.setColor(new Color(ran.nextInt(255),ran.nextInt(255),ran.nextInt(255)));
g.drawLine(ran.nextInt(width), ran.nextInt(height), ran.nextInt(width), ran.nextInt(height));
}
//10.压缩图片并输出到客户端
response.setContentType("image/jpeg");
OutputStream output=response.getOutputStream();
ImageIO.write(image, "jpeg", output);
output.close();
}

//获取随机字符串
private String getNumber(int n, Random ran) {
String number="";
String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890qwertyuiopasdfghjklzxcvbnm";
for(int i=0;i<n;i++){
number+=str.charAt(ran.nextInt(str.length()));
}
return number;
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}


我们使用的时候只需要调用对应的URL路径就能够实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: