后端Java随机生成代码
public class VerifyCodeUtil {
private static final char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
private static final int SIZE = *;
private static final int LINES = *;
private static final int WIDTH = *;
private static final int HEIGHT = *;
private static final int FONT_SIZE = *;
public static Object[] createImage() {
StringBuffer sb = new StringBuffer();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String imageDataURI = null;
try {
BufferedImage image = new BufferedImage(
WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.setColor(Color.WHITE);
graphic.fillRect(0, 0, WIDTH, HEIGHT);
Random ran = new Random();
for (int i = 0; i < SIZE; i++) {
int n = ran.nextInt(chars.length);
graphic.setColor(getRandomColor());
graphic.setFont(new Font(
"Dialog", Font.BOLD + Font.ITALIC, FONT_SIZE));
graphic.drawString(
chars[n] + "", i * WIDTH / SIZE, HEIGHT / 5 * 4 );
sb.append(chars[n]);
}
for (int i = 0; i < LINES; i++) {
graphic.setColor(getRandomColor());
graphic.drawLine(ran.nextInt(WIDTH-2), ran.nextInt(HEIGHT-2),
ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
}
ImageIO.write(image, "jpeg", baos);
imageDataURI = "data:image/jpeg;base64," + (new BASE64Encoder().encode(baos.toByteArray()));
} catch (IOException e) {
e.printStackTrace();
}finally {
return new Object[]{sb.toString().toLowerCase(), imageDataURI};
}
}
private static Color getRandomColor() {
Random ran = new Random();
Color color = new Color(ran.nextInt(230),
ran.nextInt(230), ran.nextInt(230));
return color;
}
}
controller中的调用
VerifyCodeUtil verifyCodeUtil = new VerifyCodeUtil();
Object[] objects=verifyCodeUtil.createImage();