java生成图片验证码

引言 

  小编今天身体倍感不适,头疼欲裂,所以没有办法学习比较理论的知识,在这个时候看书看视频都是没有什么效果的,但是这个时候小编喜欢敲代码,因为在敲代码的时候头疼会减轻,正好今天在看书的时候看到了一个生成验证码的例子,不过他生成的简直丑哭了,就一个黑背景和几个白色的数字,但是我们平常遇到的验证码都非常的好看还有一些朦胧的感觉。于是小编就查找了一些资料自己做了个demo。 效果展示

      

  第一种方式

  验证码工具类VerifyCodeUtils:

[java]  view plain  copy
  1. package com.verifycode.login;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics;  
  6. import java.awt.Graphics2D;  
  7. import java.awt.RenderingHints;  
  8. import java.awt.geom.AffineTransform;  
  9. import java.awt.image.BufferedImage;  
  10. import java.io.File;  
  11. import java.io.FileOutputStream;  
  12. import java.io.IOException;  
  13. import java.io.OutputStream;  
  14. import java.util.Arrays;  
  15. import java.util.Random;  
  16.   
  17. import javax.imageio.ImageIO;  
  18.   
  19. public class VerifyCodeUtils {  
  20.     // 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符  
  21.     public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";  
  22.     private static Random random = new Random();  
  23.   
  24.     /** 
  25.      * 使用系统默认字符源生成验证码 
  26.      *  
  27.      * @param verifySize 
  28.      *            验证码长度 
  29.      * @return 
  30.      */  
  31.     public static String generateVerifyCode(int verifySize) {  
  32.         return generateVerifyCode(verifySize, VERIFY_CODES);  
  33.     }  
  34.   
  35.     /** 
  36.      * 使用指定源生成验证码 
  37.      *  
  38.      * @param verifySize 
  39.      *            验证码长度 
  40.      * @param sources 
  41.      *            验证码字符源 
  42.      * @return 
  43.      */  
  44.     public static String generateVerifyCode(int verifySize, String sources) {  
  45.         if (sources == null || sources.length() == 0) {  
  46.             sources = VERIFY_CODES;  
  47.         }  
  48.         int codesLen = sources.length();  
  49.         Random rand = new Random(System.currentTimeMillis());  
  50.         StringBuilder verifyCode = new StringBuilder(verifySize);  
  51.         for (int i = 0; i < verifySize; i++) {  
  52.             verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));  
  53.         }  
  54.         return verifyCode.toString();  
  55.     }  
  56.   
  57.     /** 
  58.      * 生成随机验证码文件,并返回验证码值 
  59.      *  
  60.      * @param w 
  61.      * @param h 
  62.      * @param outputFile 
  63.      * @param verifySize 
  64.      * @return 
  65.      * @throws IOException 
  66.      */  
  67.     public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {  
  68.         String verifyCode = generateVerifyCode(verifySize);  
  69.         outputImage(w, h, outputFile, verifyCode);  
  70.         return verifyCode;  
  71.     }  
  72.   
  73.     /** 
  74.      * 输出随机验证码图片流,并返回验证码值 
  75.      *  
  76.      * @param w 
  77.      * @param h 
  78.      * @param os 
  79.      * @param verifySize 
  80.      * @return 
  81.      * @throws IOException 
  82.      */  
  83.     public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {  
  84.         String verifyCode = generateVerifyCode(verifySize);  
  85.         outputImage(w, h, os, verifyCode);  
  86.         return verifyCode;  
  87.     }  
  88.   
  89.     /** 
  90.      * 生成指定验证码图像文件 
  91.      *  
  92.      * @param w 
  93.      * @param h 
  94.      * @param outputFile 
  95.      * @param code 
  96.      * @throws IOException 
  97.      */  
  98.     public static void outputImage(int w, int h, File outputFile, String code) throws IOException {  
  99.         if (outputFile == null) {  
  100.             return;  
  101.         }  
  102.         File dir = outputFile.getParentFile();  
  103.         if (!dir.exists()) {  
  104.             dir.mkdirs();  
  105.         }  
  106.         try {  
  107.             outputFile.createNewFile();  
  108.             FileOutputStream fos = new FileOutputStream(outputFile);  
  109.             outputImage(w, h, fos, code);  
  110.             fos.close();  
  111.         } catch (IOException e) {  
  112.             throw e;  
  113.         }  
  114.     }  
  115.   
  116.     /** 
  117.      * 输出指定验证码图片流 
  118.      *  
  119.      * @param w 
  120.      * @param h 
  121.      * @param os 
  122.      * @param code 
  123.      * @throws IOException 
  124.      */  
  125.     public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {  
  126.         int verifySize = code.length();  
  127.         BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);  
  128.         Random rand = new Random();  
  129.         Graphics2D g2 = image.createGraphics();  
  130.         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);  
  131.         Color[] colors = new Color[5];  
  132.         Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW };  
  133.         float[] fractions = new float[colors.length];  
  134.         for (int i = 0; i < colors.length; i++) {  
  135.             colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];  
  136.             fractions[i] = rand.nextFloat();  
  137.         }  
  138.         Arrays.sort(fractions);  
  139.   
  140.         g2.setColor(Color.GRAY);// 设置边框色  
  141.         g2.fillRect(00, w, h);  
  142.   
  143.         Color c = getRandColor(200250);  
  144.         g2.setColor(c);// 设置背景色  
  145.         g2.fillRect(02, w, h - 4);  
  146.   
  147.         // 绘制干扰线  
  148.         Random random = new Random();  
  149.         g2.setColor(getRandColor(160200));// 设置线条的颜色  
  150.         for (int i = 0; i < 20; i++) {  
  151.             int x = random.nextInt(w - 1);  
  152.             int y = random.nextInt(h - 1);  
  153.             int xl = random.nextInt(6) + 1;  
  154.             int yl = random.nextInt(12) + 1;  
  155.             g2.drawLine(x, y, x + xl + 40, y + yl + 20);  
  156.         }  
  157.   
  158.         // 添加噪点  
  159.         float yawpRate = 0.05f;// 噪声率  
  160.         int area = (int) (yawpRate * w * h);  
  161.         for (int i = 0; i < area; i++) {  
  162.             int x = random.nextInt(w);  
  163.             int y = random.nextInt(h);  
  164.             int rgb = getRandomIntColor();  
  165.             image.setRGB(x, y, rgb);  
  166.         }  
  167.   
  168.         shear(g2, w, h, c);// 使图片扭曲  
  169.   
  170.         g2.setColor(getRandColor(100160));  
  171.         int fontSize = h - 4;  
  172.         Font font = new Font("Algerian", Font.ITALIC, fontSize);  
  173.         g2.setFont(font);  
  174.         char[] chars = code.toCharArray();  
  175.         for (int i = 0; i < verifySize; i++) {  
  176.             AffineTransform affine = new AffineTransform();  
  177.             affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);  
  178.             g2.setTransform(affine);  
  179.             g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);  
  180.         }  
  181.   
  182.         g2.dispose();  
  183.         ImageIO.write(image, "jpg", os);  
  184.     }  
  185.   
  186.     private static Color getRandColor(int fc, int bc) {  
  187.         if (fc > 255)  
  188.             fc = 255;  
  189.         if (bc > 255)  
  190.             bc = 255;  
  191.         int r = fc + random.nextInt(bc - fc);  
  192.         int g = fc + random.nextInt(bc - fc);  
  193.         int b = fc + random.nextInt(bc - fc);  
  194.         return new Color(r, g, b);  
  195.     }  
  196.   
  197.     private static int getRandomIntColor() {  
  198.         int[] rgb = getRandomRgb();  
  199.         int color = 0;  
  200.         for (int c : rgb) {  
  201.             color = color << 8;  
  202.             color = color | c;  
  203.         }  
  204.         return color;  
  205.     }  
  206.   
  207.     private static int[] getRandomRgb() {  
  208.         int[] rgb = new int[3];  
  209.         for (int i = 0; i < 3; i++) {  
  210.             rgb[i] = random.nextInt(255);  
  211.         }  
  212.         return rgb;  
  213.     }  
  214.   
  215.     private static void shear(Graphics g, int w1, int h1, Color color) {  
  216.         shearX(g, w1, h1, color);  
  217.         shearY(g, w1, h1, color);  
  218.     }  
  219.   
  220.     private static void shearX(Graphics g, int w1, int h1, Color color) {  
  221.   
  222.         int period = random.nextInt(2);  
  223.   
  224.         boolean borderGap = true;  
  225.         int frames = 1;  
  226.         int phase = random.nextInt(2);  
  227.   
  228.         for (int i = 0; i < h1; i++) {  
  229.             double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);  
  230.             g.copyArea(0, i, w1, 1, (int) d, 0);  
  231.             if (borderGap) {  
  232.                 g.setColor(color);  
  233.                 g.drawLine((int) d, i, 0, i);  
  234.                 g.drawLine((int) d + w1, i, w1, i);  
  235.             }  
  236.         }  
  237.   
  238.     }  
  239.   
  240.     private static void shearY(Graphics g, int w1, int h1, Color color) {  
  241.   
  242.         int period = random.nextInt(40) + 10// 50;  
  243.   
  244.         boolean borderGap = true;  
  245.         int frames = 20;  
  246.         int phase = 7;  
  247.         for (int i = 0; i < w1; i++) {  
  248.             double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);  
  249.             g.copyArea(i, 01, h1, 0, (int) d);  
  250.             if (borderGap) {  
  251.                 g.setColor(color);  
  252.                 g.drawLine(i, (int) d, i, 0);  
  253.                 g.drawLine(i, (int) d + h1, i, h1);  
  254.             }  
  255.   
  256.         }  
  257.   
  258.     }  
  259.   
  260.     /* 
  261.      * public static void main(String[] args) throws IOException { File dir = 
  262.      * new File("F:/verifies"); int w = 200, h = 80; for (int i = 0; i < 50; 
  263.      * i++) { String verifyCode = generateVerifyCode(4); File file = new 
  264.      * File(dir, verifyCode + ".jpg"); outputImage(w, h, file, verifyCode); } } 
  265.      */  
  266. }  

验证码servlet类(AuthImage)

[html]  view plain  copy
  1. package com.verifycode.login;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8. import javax.servlet.http.HttpSession;  
  9.   
  10. /**  
  11.  * <p>  
  12.  * <b>AuthImage Description:</b> (验证码)  
  13.  * </p>  
  14.  * <b>DATE:</b> 2016年6月2日 下午3:53:12  
  15.  */  
  16. public class AuthImage extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {  
  17.     static final long serialVersionUID = 1L;  
  18.   
  19.     public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  20.         response.setHeader("Pragma", "No-cache");  
  21.         response.setHeader("Cache-Control", "no-cache");  
  22.         response.setDateHeader("Expires", 0);  
  23.         response.setContentType("image/jpeg");  
  24.   
  25.         // 生成随机字串  
  26.         String verifyCode = VerifyCodeUtils.generateVerifyCode(4);  
  27.         // 存入会话session  
  28.         HttpSession session = request.getSession(true);  
  29.         // 删除以前的  
  30.         session.removeAttribute("verifyCode");  
  31.         session.setAttribute("verifyCode", verifyCode.toLowerCase());  
  32.         // 生成图片  
  33.         int w = 100h = 30;  
  34.         VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);  
  35.   
  36.     }  
  37. }  
 上面两个就是在效果展示的时候看到的第一个样式的验证码的两个比较重要的类,关于jsp和web.xml中的配置,在最后面一起介绍,当然我们已经非常熟悉,小编也是好长时间没有写纯servlet的demo了,感觉手都生了,所以在这顺便练习一下,这些基础的东西可不能忘掉。

  关于第一种还有一个需要强调的地方就是,上面的那种字体是调用的系统中的Algerian(在C盘的windows下面的fonts文件夹中)字体,所以如果你的系统中没有这种字体,需要下载,在文章最后小编会分享本文的源码,供读者下载。

  第二种样式

  就有一个简单的类(ImageServlet)

[html]  view plain  copy
  1. package com.verfycode.img;  
  2.   
  3. import java.awt.Color;  
  4. import java.awt.Font;  
  5. import java.awt.Graphics;  
  6. import java.awt.image.BufferedImage;  
  7. import java.io.IOException;  
  8. import java.util.Date;  
  9. import java.util.Random;  
  10.   
  11. import javax.imageio.ImageIO;  
  12. import javax.servlet.ServletException;  
  13. import javax.servlet.http.HttpServlet;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16.   
  17. public class ImageServlet extends HttpServlet {  
  18.   
  19.     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  20.         doPost(request, response);  
  21.     }  
  22.   
  23.     public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  24.         // 告诉客户端,输出的格式  
  25.         response.setContentType("image/jpeg");  
  26.   
  27.         int width = 80;  
  28.         int height = 40;  
  29.         int lines = 10;  
  30.         BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
  31.   
  32.         Graphics g = img.getGraphics();  
  33.   
  34.         // 设置背景色  
  35.         g.setColor(Color.WHITE);  
  36.         g.fillRect(0, 0, width, height);  
  37.   
  38.         // 设置字体  
  39.         g.setFont(new Font("宋体", Font.BOLD, 20));  
  40.   
  41.         // 随机数字  
  42.         Random r = new Random(new Date().getTime());  
  43.         for (int i = 0; i < 4; i++) {  
  44.             int a = r.nextInt(10);  
  45.             int y = 10 + r.nextInt(20);// 10~30范围内的一个整数,作为y坐标  
  46.   
  47.             Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));  
  48.             g.setColor(c);  
  49.   
  50.             g.drawString("" + a, 5 + i * width / 4, y);  
  51.         }  
  52.   
  53.         // 干扰线  
  54.         for (int i = 0; i < lines; i++) {  
  55.             Color c = new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255));  
  56.             g.setColor(c);  
  57.             g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));  
  58.         }  
  59.   
  60.         g.dispose();// 类似于流中的close()带动flush()---把数据刷到img对象当中  
  61.   
  62.         ImageIO.write(img, "JPG", response.getOutputStream());  
  63.     }  
  64. }  
关于jsp和web.xml中的代码小编就不在展示了,那些都是servlet最基础的东西。到这关于这两种验证码的核心代码就完了。

  至此,小编的头疼和快好得差不多了,希望能读者能有帮助。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值