看了挺多圖片驗證碼的代碼,感受沒什麼長的好看點的,就本身動手寫了個,寫完發現跟QQ的有幾分類似,比較滿意。java
功能包括:自定義圖片尺寸和字符長度,隨機背景顏色和字符顏色,隨機字符偏移角度,字符平滑邊緣,干擾線,噪點,背景扭曲。web
原本想作字符扭曲的,不知道怎的先生成文字再扭曲就報錯了,先就這樣吧,但願有高手能幫助修正一下。session
須要說明的是之因此有幾分像QQ的驗證碼感受是由於這個Algerian字體,若是系統沒有的話須要自行安裝,百度搜字體名能下載到,丟系統Fonts文件夾就行。app
JAVA文件和字體打了個包發資源裏了,http://download.csdn.net/detail/ruixue0117/7138469。dom
效果圖:字體
AuthImage類:ui
1 package hh.com.util; 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 public class AuthImage extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { 11 static final long serialVersionUID = 1L; 12 13 public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 14 response.setHeader("Pragma", "No-cache"); 15 response.setHeader("Cache-Control", "no-cache"); 16 response.setDateHeader("Expires", 0); 17 response.setContentType("image/jpeg"); 18 19 //生成隨機字串 20 String verifyCode = VerifyCodeUtils.generateVerifyCode(4); 21 //存入會話session 22 HttpSession session = request.getSession(true); 23 session.setAttribute("rand", verifyCode.toLowerCase()); 24 //生成圖片 25 int w = 200, h = 80; 26 VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode); 27 28 } 29 }
VerifyCodeUtils類(main方法可直接執行):url
1 package hh.com.util; 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.LinearGradientPaint; 8 import java.awt.Paint; 9 import java.awt.RenderingHints; 10 import java.awt.geom.AffineTransform; 11 import java.awt.image.BufferedImage; 12 import java.io.File; 13 import java.io.FileOutputStream; 14 import java.io.IOException; 15 import java.io.OutputStream; 16 import java.util.Arrays; 17 import java.util.Random; 18 19 import javax.imageio.ImageIO; 20 21 public class VerifyCodeUtils{ 22 23 //使用到Algerian字體,系統裏沒有的話須要安裝字體,字體只顯示大寫,去掉了1,0,i,o幾個容易混淆的字符 24 public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; 25 private static Random random = new Random(); 26 27 28 /** 29 * 使用系統默認字符源生成驗證碼 30 * @param verifySize 驗證碼長度 31 * @return 32 */ 33 public static String generateVerifyCode(int verifySize){ 34 return generateVerifyCode(verifySize, VERIFY_CODES); 35 } 36 /** 37 * 使用指定源生成驗證碼 38 * @param verifySize 驗證碼長度 39 * @param sources 驗證碼字符源 40 * @return 41 */ 42 public static String generateVerifyCode(int verifySize, String sources){ 43 if(sources == null || sources.length() == 0){ 44 sources = VERIFY_CODES; 45 } 46 int codesLen = sources.length(); 47 Random rand = new Random(System.currentTimeMillis()); 48 StringBuilder verifyCode = new StringBuilder(verifySize); 49 for(int i = 0; i < verifySize; i++){ 50 verifyCode.append(sources.charAt(rand.nextInt(codesLen-1))); 51 } 52 return verifyCode.toString(); 53 } 54 55 /** 56 * 生成隨機驗證碼文件,並返回驗證碼值 57 * @param w 58 * @param h 59 * @param outputFile 60 * @param verifySize 61 * @return 62 * @throws IOException 63 */ 64 public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{ 65 String verifyCode = generateVerifyCode(verifySize); 66 outputImage(w, h, outputFile, verifyCode); 67 return verifyCode; 68 } 69 70 /** 71 * 輸出隨機驗證碼圖片流,並返回驗證碼值 72 * @param w 73 * @param h 74 * @param os 75 * @param verifySize 76 * @return 77 * @throws IOException 78 */ 79 public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{ 80 String verifyCode = generateVerifyCode(verifySize); 81 outputImage(w, h, os, verifyCode); 82 return verifyCode; 83 } 84 85 /** 86 * 生成指定驗證碼圖像文件 87 * @param w 88 * @param h 89 * @param outputFile 90 * @param code 91 * @throws IOException 92 */ 93 public static void outputImage(int w, int h, File outputFile, String code) throws IOException{ 94 if(outputFile == null){ 95 return; 96 } 97 File dir = outputFile.getParentFile(); 98 if(!dir.exists()){ 99 dir.mkdirs(); 100 } 101 try{ 102 outputFile.createNewFile(); 103 FileOutputStream fos = new FileOutputStream(outputFile); 104 outputImage(w, h, fos, code); 105 fos.close(); 106 } catch(IOException e){ 107 throw e; 108 } 109 } 110 111 /** 112 * 輸出指定驗證碼圖片流 113 * @param w 114 * @param h 115 * @param os 116 * @param code 117 * @throws IOException 118 */ 119 public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{ 120 int verifySize = code.length(); 121 BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); 122 Random rand = new Random(); 123 Graphics2D g2 = image.createGraphics(); 124 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON); 125 Color[] colors = new Color[5]; 126 Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN, 127 Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, 128 Color.PINK, Color.YELLOW }; 129 float[] fractions = new float[colors.length]; 130 for(int i = 0; i < colors.length; i++){ 131 colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)]; 132 fractions[i] = rand.nextFloat(); 133 } 134 Arrays.sort(fractions); 135 136 g2.setColor(Color.GRAY);// 設置邊框色 137 g2.fillRect(0, 0, w, h); 138 139 Color c = getRandColor(200, 250); 140 g2.setColor(c);// 設置背景色 141 g2.fillRect(0, 2, w, h-4); 142 143 //繪製干擾線 144 Random random = new Random(); 145 g2.setColor(getRandColor(160, 200));// 設置線條的顏色 146 for (int i = 0; i < 20; i++) { 147 int x = random.nextInt(w - 1); 148 int y = random.nextInt(h - 1); 149 int xl = random.nextInt(6) + 1; 150 int yl = random.nextInt(12) + 1; 151 g2.drawLine(x, y, x + xl + 40, y + yl + 20); 152 } 153 154 // 添加噪點 155 float yawpRate = 0.05f;// 噪聲率 156 int area = (int) (yawpRate * w * h); 157 for (int i = 0; i < area; i++) { 158 int x = random.nextInt(w); 159 int y = random.nextInt(h); 160 int rgb = getRandomIntColor(); 161 image.setRGB(x, y, rgb); 162 } 163 164 shear(g2, w, h, c);// 使圖片扭曲 165 166 g2.setColor(getRandColor(100, 160)); 167 int fontSize = h-4; 168 Font font = new Font("Algerian", Font.ITALIC, fontSize); 169 g2.setFont(font); 170 char[] chars = code.toCharArray(); 171 for(int i = 0; i < verifySize; i++){ 172 AffineTransform affine = new AffineTransform(); 173 affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2); 174 g2.setTransform(affine); 175 g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10); 176 } 177 178 g2.dispose(); 179 ImageIO.write(image, "jpg", os); 180 } 181 182 private static Color getRandColor(int fc, int bc) { 183 if (fc > 255) 184 fc = 255; 185 if (bc > 255) 186 bc = 255; 187 int r = fc + random.nextInt(bc - fc); 188 int g = fc + random.nextInt(bc - fc); 189 int b = fc + random.nextInt(bc - fc); 190 return new Color(r, g, b); 191 } 192 193 private static int getRandomIntColor() { 194 int[] rgb = getRandomRgb(); 195 int color = 0; 196 for (int c : rgb) { 197 color = color << 8; 198 color = color | c; 199 } 200 return color; 201 } 202 203 private static int[] getRandomRgb() { 204 int[] rgb = new int[3]; 205 for (int i = 0; i < 3; i++) { 206 rgb[i] = random.nextInt(255); 207 } 208 return rgb; 209 } 210 211 private static void shear(Graphics g, int w1, int h1, Color color) { 212 shearX(g, w1, h1, color); 213 shearY(g, w1, h1, color); 214 } 215 216 private static void shearX(Graphics g, int w1, int h1, Color color) { 217 218 int period = random.nextInt(2); 219 220 boolean borderGap = true; 221 int frames = 1; 222 int phase = random.nextInt(2); 223 224 for (int i = 0; i < h1; i++) { 225 double d = (double) (period >> 1) 226 * Math.sin((double) i / (double) period 227 + (6.2831853071795862D * (double) phase) 228 / (double) frames); 229 g.copyArea(0, i, w1, 1, (int) d, 0); 230 if (borderGap) { 231 g.setColor(color); 232 g.drawLine((int) d, i, 0, i); 233 g.drawLine((int) d + w1, i, w1, i); 234 } 235 } 236 237 } 238 239 private static void shearY(Graphics g, int w1, int h1, Color color) { 240 241 int period = random.nextInt(40) + 10; // 50; 242 243 boolean borderGap = true; 244 int frames = 20; 245 int phase = 7; 246 for (int i = 0; i < w1; i++) { 247 double d = (double) (period >> 1) 248 * Math.sin((double) i / (double) period 249 + (6.2831853071795862D * (double) phase) 250 / (double) frames); 251 g.copyArea(i, 0, 1, h1, 0, (int) d); 252 if (borderGap) { 253 g.setColor(color); 254 g.drawLine(i, (int) d, i, 0); 255 g.drawLine(i, (int) d + h1, i, h1); 256 } 257 258 } 259 260 } 261 public static void main(String[] args) throws IOException{ 262 File dir = new File("F:/verifies"); 263 int w = 200, h = 80; 264 for(int i = 0; i < 50; i++){ 265 String verifyCode = generateVerifyCode(4); 266 File file = new File(dir, verifyCode + ".jpg"); 267 outputImage(w, h, file, verifyCode); 268 } 269 } 270 }
web.xml配置:spa
1 <servlet> 2 <servlet-name>AuthImage</servlet-name> 3 <servlet-class>hh.com.util.AuthImage</servlet-class> 4 </servlet> 5 <servlet-mapping> 6 <servlet-name>AuthImage</servlet-name> 7 <url-pattern>/authImage</url-pattern> 8 </servlet-mapping>