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
| package com.laisc.wisefire_read.controller;
import java.awt.*; import java.awt.image.BufferedImage; import java.util.Random;
public class ValidateCodeUtil {
private static Random random = new Random(); private int width = 165; private int height = 45; private int lineSize = 30; private int lineLength = 20; private int randomStrNum = 4; private int colorMin = 0; private int colorMax = 127; private String randomString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWSYZ"; Font font = new Font("Times New Roman", Font.ROMAN_BASELINE, 40);
private Color getRandomColor() { int r = (int)(Math.random()*(colorMax-colorMin+1)+colorMin); int g = (int)(Math.random()*(colorMax-colorMin+1)+colorMin); int b = (int)(Math.random()*(colorMax-colorMin+1)+colorMin);
return new Color(r, g, b); }
private void drawLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(lineLength); int yl = random.nextInt(lineLength); g.drawLine(x, y, x + xl, y + yl);
}
public BufferedImage getRandomCodeImage(){
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics(); g.fillRect(0, 0, width, height); g.setColor(getRandomColor()); g.setFont(font); for (int i = 0; i < lineSize; i++) { drawLine(g); } String randomStr = ""; for (int i = 0; i < randomStrNum; i++) { g.setFont(font); g.setColor(getRandomColor()); String str = String.valueOf(randomString.charAt(random.nextInt(randomString.length()))); g.translate(random.nextInt(3), random.nextInt(6)); g.drawString(str, 40 * i + 10, 25); } g.dispose(); return image; } }
|