Java代码随机生成图片验证码

朱雀 2022-07-16 01:09 384阅读 0赞

-—ValidateCode.java 验证码生成类
package cn.dsna.util.images;

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

import javax.imageio.ImageIO;
/**
* 验证码生成器
* @author dsna
*
*/
public class ValidateCode {
// 图片的宽度。
private int width = 160;
// 图片的高度。
private int height = 40;
// 验证码字符个数
private int codeCount = 5;
// 验证码干扰线数
private int lineCount = 150;
// 验证码
private String code = null;
// 验证码图片Buffer
private BufferedImage buffImg=null;

  1. private char\[\] codeSequence = \{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
  2. 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
  3. 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' \};
  4. public ValidateCode() \{
  5. this.createCode();
  6. \}
  7. /\*\*
  8. \*
  9. \* @param width 图片宽
  10. \* @param height 图片高
  11. \*/
  12. public ValidateCode(int width,int height) \{
  13. this.width=width;
  14. this.height=height;
  15. this.createCode();
  16. \}
  17. /\*\*
  18. \*
  19. \* @param width 图片宽
  20. \* @param height 图片高
  21. \* @param codeCount 字符个数
  22. \* @param lineCount 干扰线条数
  23. \*/
  24. public ValidateCode(int width,int height,int codeCount,int lineCount) \{
  25. this.width=width;
  26. this.height=height;
  27. this.codeCount=codeCount;
  28. this.lineCount=lineCount;
  29. this.createCode();
  30. \}
  31. public void createCode() \{
  32. int x = 0,fontHeight=0,codeY=0;
  33. int red = 0, green = 0, blue = 0;
  34. x = width / (codeCount +2);//每个字符的宽度
  35. fontHeight = height - 2;//字体的高度
  36. codeY = height - 4;
  37. // 图像buffer
  38. buffImg = new BufferedImage(width, height,BufferedImage.TYPE\_INT\_RGB);
  39. Graphics2D g = buffImg.createGraphics();
  40. // 生成随机数
  41. Random random = new Random();
  42. // 将图像填充为白色
  43. g.setColor(Color.WHITE);
  44. g.fillRect(0, 0, width, height);
  45. // 创建字体
  46. ImgFontByte imgFont=new ImgFontByte();
  47. Font font =imgFont.getFont(fontHeight);
  48. g.setFont(font);
  49. for (int i = 0; i < lineCount; i++) \{
  50. int xs = random.nextInt(width);
  51. int ys = random.nextInt(height);
  52. int xe = xs+random.nextInt(width/8);
  53. int ye = ys+random.nextInt(height/8);
  54. red = random.nextInt(255);
  55. green = random.nextInt(255);
  56. blue = random.nextInt(255);
  57. g.setColor(new Color(red, green, blue));
  58. g.drawLine(xs, ys, xe, ye);
  59. \}
  60. // randomCode记录随机产生的验证码
  61. StringBuffer randomCode = new StringBuffer();
  62. // 随机产生codeCount个字符的验证码。
  63. for (int i = 0; i < codeCount; i++) \{
  64. String strRand = String.valueOf(codeSequence\[random.nextInt(codeSequence.length)\]);
  65. // 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
  66. red = random.nextInt(255);
  67. green = random.nextInt(255);
  68. blue = random.nextInt(255);
  69. g.setColor(new Color(red, green, blue));
  70. g.drawString(strRand, (i + 1) \* x, codeY);
  71. // 将产生的四个随机数组合在一起。
  72. randomCode.append(strRand);
  73. \}
  74. // 将四位数字的验证码保存到Session中。
  75. code=randomCode.toString();
  76. \}
  77. public void write(String path) throws IOException \{
  78. OutputStream sos = new FileOutputStream(path);
  79. this.write(sos);
  80. \}
  81. public void write(OutputStream sos) throws IOException \{
  82. ImageIO.write(buffImg, "png", sos);
  83. sos.close();
  84. \}
  85. public BufferedImage getBuffImg() \{
  86. return buffImg;
  87. \}
  88. public String getCode() \{
  89. return code;
  90. \}

}

-—ImgFontByte.java

package cn.dsna.util.images;
import java.io.ByteArrayInputStream;
import java.awt.*;
/**
* ttf字体文件
* @author dsna
*
*/
public class ImgFontByte {
public Font getFont(int fontHeight){
try {
Font baseFont = Font.createFont(Font.TRUETYPE_FONT, new ByteArrayInputStream(hex2byte(getFontByteStr())));
return baseFont.deriveFont(Font.PLAIN, fontHeight);
} catch (Exception e) {
return new Font(“Arial”,Font.PLAIN, fontHeight);
}
}

  1. private byte\[\] hex2byte(String str) \{
  2. if (str == null)
  3. return null;
  4. str = str.trim();
  5. int len = str.length();
  6. if (len == 0 || len % 2 == 1)
  7. return null;
  8. byte\[\] b = new byte\[len / 2\];
  9. try \{
  10. for (int i = 0; i < str.length(); i += 2) \{
  11. b\[i / 2\] = (byte) Integer
  12. .decode("0x" + str.substring(i, i + 2)).intValue();
  13. \}
  14. return b;
  15. \} catch (Exception e) \{
  16. return null;
  17. \}
  18. \} /\*\*

* ttf字体文件的十六进制字符串
* @return
*/
private String getFontByteStr(){ return null;
return str;//字符串太长 在附件中找
}
}

-—ValidateCodeServlet.java Servlet调用方法
package cn.dsna.util.images;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ValidateCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

  1. @Override
  2. protected void doGet(HttpServletRequest reqeust,
  3. HttpServletResponse response) throws ServletException, IOException \{
  4. // 设置响应的类型格式为图片格式
  5. response.setContentType("image/jpeg");
  6. //禁止图像缓存。
  7. response.setHeader("Pragma", "no-cache");
  8. response.setHeader("Cache-Control", "no-cache");
  9. response.setDateHeader("Expires", 0);
  10. HttpSession session = reqeust.getSession();
  11. ValidateCode vCode = new ValidateCode(120,40,5,100);
  12. session.setAttribute("code", vCode.getCode());
  13. vCode.write(response.getOutputStream());
  14. \}

/**
* web.xml 添加servlet

validateCodeServlet
cn.dsna.util.images.ValidateCodeServlet


validateCodeServlet
*.images

在地址栏输入XXX/dsna.images 测试
*/

}
-——ValidateCodeTest.java测试类

package cn.dsna.util.images;

import java.io.IOException;
import java.util.Date;

public class ValidateCodeTest {

  1. /\*\*
  2. \* @param args
  3. \*/
  4. public static void main(String\[\] args) \{
  5. ValidateCode vCode = new ValidateCode(120,40,5,100);
  6. try \{
  7. String path="D:/t/"+new Date().getTime()+".png";
  8. System.out.println(vCode.getCode()+" >"+path);
  9. vCode.write(path);
  10. \} catch (IOException e) \{
  11. e.printStackTrace();
  12. \}
  13. \}

}

-—-web.xml 配置


validateCodeServlet
cn.dsna.util.images.ValidateCodeServlet


validateCodeServlet
*.images

发表评论

表情:
评论列表 (有 0 条评论,384人围观)

还没有评论,来说两句吧...

相关阅读