java 生成动态验证码
话不多说直接上干货
1 public static void main(String[] args) throws IOException { 2 BufferedImage image = new BufferedImage(108, 40, 1); 3 drawGraphic("gs45", image); 4 File file = new File("d://abc.jpeg"); 5 ImageIO.write(image, "jpeg", file); 6 7 8 } 9 protected static final char[] charArray = "3456789ABCDEFGHJKMNPQRSTUVWXY".toCharArray(); 10 protected static final Font[] RANDOM_FONT = new Font[]{new Font("Dialog", 1, 33), new Font("DialogInput", 1, 34), new Font("Serif", 1, 33), new Font("SansSerif", 1, 34), new Font("Monospaced", 1, 34)}; 11 public static void drawGraphic(String randomString, BufferedImage image) { 12 Graphics2D g = image.createGraphics(); 13 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); 14 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 15 g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); 16 ThreadLocalRandom random = ThreadLocalRandom.current(); 17 g.setColor(getRandomColor(210, 250, random)); 18 g.fillRect(0, 0, 108, 40); 19 Color color = null; 20 21 int i; 22 for(i = 0; i < 20; ++i) { 23 color = getRandomColor(120, 200, random); 24 g.setColor(color); 25 String rand = String.valueOf(charArray[random.nextInt(charArray.length)]); 26 g.drawString(rand, random.nextInt(108), random.nextInt(40)); 27 color = null; 28 } 29 30 g.setFont(RANDOM_FONT[random.nextInt(RANDOM_FONT.length)]); 31 32 for(i = 0; i < randomString.length(); ++i) { 33 int degree = random.nextInt(28); 34 if (i % 2 == 0) { 35 degree *= -1; 36 } 37 38 int x = 22 * i; 39 int y = 21; 40 g.rotate(Math.toRadians((double)degree), (double)x, (double)y); 41 color = getRandomColor(20, 130, random); 42 g.setColor(color); 43 g.drawString(String.valueOf(randomString.charAt(i)), x + 8, y + 10); 44 g.rotate(-Math.toRadians((double)degree), (double)x, (double)y); 45 } 46 47 g.setColor(color); 48 BasicStroke bs = new BasicStroke(3.0F); 49 g.setStroke(bs); 50 QuadCurve2D.Double curve = new QuadCurve2D.Double(0.0D, (double)(random.nextInt(32) + 4), 54.0D, 20.0D, 108.0D, (double)(random.nextInt(32) + 4)); 51 g.draw(curve); 52 g.dispose(); 53 } 54 55 public static Color getRandomColor(int fc, int bc, ThreadLocalRandom random) { 56 if (fc > 255) { 57 fc = 255; 58 } 59 60 if (bc > 255) { 61 bc = 255; 62 } 63 64 int r = fc + random.nextInt(bc - fc); 65 int g = fc + random.nextInt(bc - fc); 66 int b = fc + random.nextInt(bc - fc); 67 return new Color(r, g, b); 68 }
效果图:
本文来自博客园,作者:lanwf,转载请注明原文链接:https://www.cnblogs.com/lccsdncnblogs/p/16625442.html