java生成图形验证码_【Java】生成图形验证码

这是一个Java类,用于生成图形验证码。代码定义了生成验证码字符串的方法,并提供了输出到文件或流的功能。验证码图片包含随机字符,有干扰线和噪点,且字符可以扭曲。字体选择了Algerian,去除了易混淆的字符。
摘要由CSDN通过智能技术生成

1 packagecom.util;2

3 importjava.awt.Color;4 importjava.awt.Font;5 importjava.awt.Graphics;6 importjava.awt.Graphics2D;7 importjava.awt.RenderingHints;8 importjava.awt.geom.AffineTransform;9 importjava.awt.image.BufferedImage;10 importjava.io.File;11 importjava.io.FileOutputStream;12 importjava.io.IOException;13 importjava.io.OutputStream;14 importjava.util.Arrays;15 importjava.util.Random;16

17 importjavax.imageio.ImageIO;18

19

20 public classVerifyCodeUtils {21

22 //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符

23 public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";24 private static Random random = newRandom();25

26

27 /**

28 * 使用系统默认字符源生成验证码29 *@paramverifySize 验证码长度30 *@return

31 */

32 public static String generateVerifyCode(intverifySize){33 returngenerateVerifyCode(verifySize, VERIFY_CODES);34 }35

36 /**

37 * 使用指定源生成验证码38 *@paramverifySize 验证码长度39 *@paramsources 验证码字符源40 *@return

41 */

42 public static String generateVerifyCode(intverifySize, String sources){43 if(sources == null || sources.length() == 0){44 sources =VERIFY_CODES;45 }46 int codesLen =sources.length();47 Random rand = newRandom(System.currentTimeMillis());48 StringBuilder verifyCode = newStringBuilder(verifySize);49 for(int i = 0; i < verifySize; i++){50 verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));51 }52 returnverifyCode.toString();53 }54

55 /**

56 * 生成随机验证码文件,并返回验证码值57 *@paramw58 *@paramh59 *@paramoutputFile60 *@paramverifySize61 *@return

62 *@throwsIOException63 */

64 public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throwsIOException{65 String verifyCode =generateVerifyCode(verifySize);66 outputImage(w, h, outputFile, verifyCode);67 returnverifyCode;68 }69

70 /**

71 * 输出随机验证码图片流,并返回验证码值72 *@paramw73 *@paramh74 *@paramos75 *@paramverifySize76 *@return

77 *@throwsIOException78 */

79 public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throwsIOException{80 String verifyCode =generateVerifyCode(verifySize);81 outputImage(w, h, os, verifyCode);82 returnverifyCode;83 }84

85 /**

86 * 生成指定验证码图像文件87 *@paramw88 *@paramh89 *@paramoutputFile90 *@paramcode91 *@throwsIOException92 */

93 public static void outputImage(int w, int h, File outputFile, String code) throwsIOException{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 = newFileOutputStream(outputFile);104 outputImage(w, h, fos, code);105 fos.close();106 } catch(IOException e){107 throwe;108 }109 }110

111 /**

112 * 输出指定验证码图片流113 *@paramw114 *@paramh115 *@paramos116 *@paramcode117 *@throwsIOException118 */

119 public static void outputImage(int w, int h, OutputStream os, String code) throwsIOException{120 int verifySize =code.length();121 BufferedImage image = newBufferedImage(w, h, BufferedImage.TYPE_INT_RGB);122 Random rand = newRandom();123 Graphics2D g2 =image.createGraphics();124 g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);125 Color[] colors = new Color[5];126 Color[] colorSpaces = newColor[] { 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 = newRandom();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 = newAffineTransform();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, "png", os);180 }181

182 private static Color getRandColor(int fc, intbc) {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 newColor(r, g, b);191 }192

193 private static intgetRandomIntColor() {194 int[] rgb =getRandomRgb();195 int color = 0;196 for (intc : rgb) {197 color = color << 8;198 color = color |c;199 }200 returncolor;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 returnrgb;209 }210

211 private static void shear(Graphics g, int w1, inth1, 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, inth1, 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) period227 + (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, inth1, 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) period249 + (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 public static void main(String[] args) throwsIOException{261 File dir = new File("C:/Users/H__D/Desktop/");262 int w = 200, h = 80;263 String verifyCode = generateVerifyCode(4);264 File file = new File(dir, verifyCode + ".jpg");265 outputImage(w, h, file, verifyCode);266 }267 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值