Java生成验证码
1 import java.awt.*; 2 import java.awt.image.BufferedImage; 3 import java.io.*; 4 import java.util.Random; 5 import javax.imageio.ImageIO; 6 7 public class ValidationCode { 8 9 // 图形验证码的字符集合,系统将随机从这个字符串中选择一些字符作为验证码 10 private static String codeChars = "%#23456789abcdefghkmnpqrstuvwxyzABCDEFGHKLMNPQRSTUVWXYZ"; 11 12 // 返回一个随机颜色(Color对象) 13 private static Color getRandomColor(int minColor, int maxColor) { 14 Random random = new Random(); 15 // 保存minColor最大不会超过255 16 if (minColor > 255) 17 minColor = 255; 18 // 保存minColor最大不会超过255 19 if (maxColor > 255) 20 maxColor = 255; 21 // 获得红色的随机颜色值 22 int red = minColor + random.nextInt(maxColor - minColor); 23 // 获得绿色的随机颜色值 24 int green = minColor + random.nextInt(maxColor - minColor); 25 // 获得蓝色的随机颜色值 26 int blue = minColor + random.nextInt(maxColor - minColor); 27 return new Color(red, green, blue); 28 } 29 30 protected static void getValidationCode() throws IOException { 31 try { 32 // 获得验证码集合的长度 33 int charsLength = codeChars.length(); 34 // 设置图形验证码的长和宽(图形的大小) 35 int width = 90, height = 30; 36 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 37 Graphics g = image.getGraphics();// 获得用于输出文字的Graphics对象 38 Random random = new Random(); 39 g.setColor(getRandomColor(180, 250));// 随机设置要填充的颜色 40 g.fillRect(0, 0, width, height);// 填充图形背景 41 // 设置初始字体 42 g.setFont(new Font("Times New Roman", Font.ITALIC, height)); 43 g.setColor(getRandomColor(120, 180));// 随机设置字体颜色 44 // 用于保存最后随机生成的验证码 45 StringBuilder validationCode = new StringBuilder(); 46 // 验证码的随机字体 47 String[] fontNames = { "Times New Roman", "Book antiqua", "Arial" }; 48 // 随机生成3个到5个验证码 49 for (int i = 0; i < 3 + random.nextInt(3); i++) { 50 // 随机设置当前验证码的字符的字体 51 g.setFont(new Font(fontNames[random.nextInt(3)], Font.ITALIC, height)); 52 // 随机获得当前验证码的字符 53 char codeChar = codeChars.charAt(random.nextInt(charsLength)); 54 validationCode.append(codeChar); 55 // 随机设置当前验证码字符的颜色 56 g.setColor(getRandomColor(10, 100)); 57 // 在图形上输出验证码字符,x和y都是随机生成的 58 g.drawString(String.valueOf(codeChar), 16 * i + random.nextInt(7), height - random.nextInt(6)); 59 } 60 File file = new File("d:\\code.png"); 61 ImageIO.write(image, "png", file); 62 System.out.println(validationCode.toString()); 63 //byte[] data = ((DataBufferByte) image.getData().getDataBuffer()).getData(); 64 g.dispose(); 65 } catch (Exception e) { 66 e.printStackTrace(); 67 } 68 } 69 70 public static void main(String[] args) throws IOException{ 71 getValidationCode(); 72 } 73 }