1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
public class VerificationCode { private static final String[] randomStr = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
public static Map getVerificationCode() { return getVerificationCodeWithStr(null); }
public static Map getVerificationCodeWithStr(String str) { int strLength = 4; char[] strArr = null; if (StringUtils.isNotEmpty(str)) { strLength = str.length(); strArr = str.toCharArray(); }
int width = 20 * strLength + 5, height = 25; BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = bufferedImage.createGraphics(); graphics2D.setColor(Color.WHITE); graphics2D.fillRect(0, 0, width, height);
if (StringUtils.isNotEmpty(str)) { graphics2D.setColor(Color.WHITE); } else { graphics2D.setColor(Color.GRAY); } Random random = new Random(); for (int i = 0; i < 100; i++) { graphics2D.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height)); }
Font font = new Font("Times New Roman", Font.BOLD, 25); graphics2D.setFont(font);
StringBuffer sb = new StringBuffer(); for (int i = 0; i < strLength; i++) { String randomNumber = randomStr[random.nextInt(36)]; if (StringUtils.isNotEmpty(str)) { randomNumber = String.valueOf(strArr[i]); }
int red = random.nextInt(255); int green = random.nextInt(255); int blue = random.nextInt(255); graphics2D.setColor(new Color(red, green, blue)); if (null != randomNumber) { graphics2D.drawString(randomNumber, 20 * i + 5, (height / 2) + 10); sb.append(randomNumber); } } bufferedImage.flush(); graphics2D.dispose();
Map result = new HashMap(); result.put("imgStream", bufferedImage); result.put("code", str); return result; } }
|