在注册帐号的时候,经常出现那种随机认证图片,每次刷新都会变化而且有些干扰和旋转功能,防止恶意注册,但是这个东西到底是怎么做的呢,下面使用Servlet来实现这个功能,其实很简单,一个Servlet搞定,下面是上代码
package com.bird.ServletResponse; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; 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 ResponseImage extends HttpServlet { /** * @use 实现随机图片的生成 * @author Bird */ private static final long serialVersionUID = 1L; private static final int WIDTH = 120; private static final int HEIGHT = 35; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //在内出中创建一个图片 BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics();//得到图形 //1.设置背景颜色 setBackGound(g); //2.设置边框 setBorder(g); //3.画干扰线 drwaRandomLine(g); //4.写随机数 drawRandomNum((Graphics2D)g); //5.写给浏览器 response.setContentType("image/jpeg");//设置浏览器打开方式 response.setDateHeader("expries", -1);//设置他们不用Cache response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); ImageIO.write(image, "jpg", response.getOutputStream()); } private void drawRandomNum(Graphics2D g) { g.setColor(Color.RED); g.setFont(new Font("宋体",Font.BOLD,20)); String base = "\u7684\u4e00\u662f\u6621\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a"; //所有汉字在\u4e00---\u9fa5 int x = 5; for(int i = 0; i < 4; i++){ int degree = new Random().nextInt()%30;//旋转弧度 String ch = base.charAt(new Random().nextInt(base.length()))+""; g.rotate(degree*Math.PI/180, x, 20);//设置旋转弧度 // System.out.println(ch+"\n"); g.drawString(ch, x, 20); g.rotate(-degree*Math.PI/180, x, 20);//旋转回来才能进行下次旋转 x+=30; } } private void drwaRandomLine(Graphics g) { g.setColor(Color.GREEN); for(int i = 0; i < 5; i++){ int x1 = new Random().nextInt(WIDTH); int y1 = new Random().nextInt(HEIGHT); int x2 = new Random().nextInt(WIDTH); int y2 = new Random().nextInt(HEIGHT); g.drawLine(x1, y1, x2, y2); } } private void setBorder(Graphics g) { g.setColor(Color.BLUE); g.drawRect(1, 1, WIDTH-2, HEIGHT-2); } private void setBackGound(Graphics g) { g.setColor(Color.WHITE); g.fillRect(0, 0, WIDTH, HEIGHT); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
然后写到一个网页上面去,当然,没有任何修饰,见笑
最终效果如下