歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java生成驗證碼

Java生成驗證碼

日期:2017/3/1 10:39:23   编辑:Linux編程
Java生成驗證碼
  1. package cn.net.seek.util;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.image.BufferedImage;
  6. import java.io.IOException;
  7. import java.io.OutputStream;
  8. import java.util.Random;
  9. import javax.imageio.ImageIO;
  10. public class ImgZoom {
  11. // 驗證碼圖片中可以出現的字符集,可根據需要修改
  12. private char mapTable[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
  13. 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
  14. 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
  15. 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
  16. 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
  17. '9' };
  18. /**
  19. * 生成驗證碼
  20. * @param width 寬度 60
  21. * @param height 高度 24
  22. * @param os 輸出流
  23. * @return 生成的隨機字符串
  24. */
  25. public String getCertPic(int width, int height, OutputStream os) {
  26. BufferedImage image = new BufferedImage(width, height,
  27. BufferedImage.TYPE_INT_RGB);
  28. // 獲取圖形上下文
  29. Graphics g = image.getGraphics();
  30. // 生成隨機類
  31. Random random = new Random();
  32. // 設定背景色
  33. // g.setColor(getRandColor(200, 250)); //隨機生成背景色
  34. g.setColor(new Color(255, 255, 255));
  35. g.fillRect(0, 0, width, height);
  36. // 設定字體
  37. g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
  38. // 隨機產生155條干擾線,使圖象中的認證碼不易被其它程序探測到
  39. g.setColor(getRandColor(160, 200));
  40. for (int i = 0; i < 155; i++) {
  41. int x = random.nextInt(width);
  42. int y = random.nextInt(height);
  43. int xl = random.nextInt(12);
  44. int yl = random.nextInt(12);
  45. g.drawLine(x, y, x + xl, y + yl);
  46. }
  47. // 取隨機產生的認證碼(5位)
  48. String sRand = "";
  49. for (int i = 0; i < 5; i++) {
  50. String rand = mapTable[(int) (mapTable.length * Math.random())]
  51. + "";
  52. sRand += rand;
  53. // 將認證碼顯示到圖象中
  54. g.setColor(new Color(20 + random.nextInt(110), 20 + random
  55. .nextInt(110), 20 + random.nextInt(110)));// 調用函數出來的顏色相同,可能是因為種子太接近,所以只能直接生成
  56. g.drawString(rand, 10 * i + 3, (int) (Math.random() * 9 + 14));// 14-23 Math.round(Math.random()*(Max-Min)+Min)
  57. }
  58. // 釋放圖形上下文
  59. g.dispose();
  60. try {
  61. // 輸出圖象到頁面
  62. ImageIO.write(image, "JPEG", os);
  63. } catch (IOException e) {
  64. return "";
  65. }
  66. return sRand;
  67. }
  68. Color getRandColor(int fc, int bc) {
  69. // 給定范圍獲得隨機顏色
  70. Random random = new Random();
  71. if (fc > 255)
  72. fc = 255;
  73. if (bc > 255)
  74. bc = 255;
  75. int r = fc + random.nextInt(bc - fc);
  76. int g = fc + random.nextInt(bc - fc);
  77. int b = fc + random.nextInt(bc - fc);
  78. return new Color(r, g, b);
  79. }
  80. }
Copyright © Linux教程網 All Rights Reserved