随机生成图片验证码
2017-12-23 17:27
344 查看
在做项目的时候,我们经常也会用到随机数验证码,下面带大家一起实现验证码的绘制实现过程:
我们使用的时候只需要调用对应的URL路径就能够实现。
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路径就能够实现。
相关文章推荐
- 【java】图片验证码的随机生成
- LedPedometer-3.注册界面和Android随机生成图片验证码
- Java如何随机生成图片验证码
- 随机生成6位图片验证码
- java生成随机图片验证码
- Java代码随机生成图片验证码
- 随机生成图片验证码
- 关于如何用JAVA代码生成随机图片验证码
- 随机生成图片验证码
- 生成随机图片验证码
- Android自定义View绘制随机生成图片验证码
- python生成随机图片验证码
- 随机生成图片验证码
- Java Web:使用Servlet生成网页随机图片验证码
- 随机生成图片验证码
- Python 生成随机图片验证码
- 随机生成图片验证码(C#)
- servletResponse 随机生成图片验证码
- Android 自定义View之随机生成图片验证码
- java生成图片验证码二,加入透明颜色,各种干扰线,干扰点,干扰框,旋转,随机位置