Java生成验证码合集(一)简单版

这种:

验证码

Java  代码、 SpringMVC  方式的Controller代码。

 
  1. @RequestMapping(value="getYzm",method=RequestMethod.GET)
  2. public void getYzm(HttpServletResponse response,HttpServletRequest request){
  3. try {
  4. response.setHeader("Pragma", "No-cache");
  5. response.setHeader("Cache-Control", "no-cache");
  6. response.setDateHeader("Expires", 0);
  7. response.setContentType("image/jpeg");
  8.  
  9. //生成随机字串
  10. String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
  11. //存入会话session
  12. HttpSession session = request.getSession(true);
  13. session.setAttribute("_code", verifyCode.toLowerCase());
  14. //生成图片
  15. int w = 146, h = 33;
  16. VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
  17. } catch (Exception e) {
  18. LoggerUtils.fmtError(getClass(),e, "获取验证码异常:%s",e.getMessage());
  19. }
  20. }

下面给出Javascript代码。

 
  1. <#-- 获取验证码 -->
  2. $("#getYzm").click(function(){
  3. var url = "http://www.sojson.com/getYzm.shtml?t=" + Math.random();
  4. this.src = url;
  5. }).click().show();

这里用到一个工具类。VerifyCodeUtils.java。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值