使用java中Graphics2D绘制验证码并获取图片,代码如下:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class VerifyCode {
public static void main(String[] args) {
int w = 200;
int h = 100;
Random r = new Random();
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
// 抗锯齿
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
g.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, w, h);
g.setColor(new Color(r.nextInt(0, 256), r.nextInt(0, 256), r.nextInt(0, 256), r.nextInt(190, 256)));
Font font = new Font("微软雅黑", Font.BOLD, 50);
g.setFont(font);
FontMetrics fm = g.getFontMetrics(font);
int ascent = fm.getAscent();
String code = getVerifyCode(4);
System.out.println(code);
try {
for (int i = 0; i < 4; i++) {
g.drawString(String.valueOf(code.charAt(i)), r.nextInt(i * 40 + 20, i * 40 + 40), r.nextInt(ascent, h - 10));
}
ImageIO.write(bi, "jpg", new File("H:\\javaTest\\demo2\\src\\com\\bufferedGraphics\\05.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
// 添加字母干扰
addStringDisturbance(30, g, w, h);
// 直线干扰
addLineDisturbance(5, g, w, h);
try {
ImageIO.write(bi, "jpg", new File("H:\\javaTest\\demo2\\src\\com\\bufferedGraphics\\05.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
g.dispose();
}
/**
* 获取验证码
*
* @param num 指定验证码的位数
* @return 验证码
*/
public static String getVerifyCode(int num) {
String str = "abcdefghijklmnopqrstuvwxyz1234567890";
StringBuilder sb = new StringBuilder();
Random r = new Random();
for (int i = 0; i < num; i++) {
sb.append(str.charAt(r.nextInt(0, str.length())));
}
return sb.toString();
}
/**
* 添加字母干扰
*
* @param num 干扰字母数量
* @param g 画笔对象
* @param w 画布宽
* @param h 画布高
*/
public static void addStringDisturbance(int num, Graphics2D g, int w, int h) {
Font font;
Random r = new Random();
String str = getVerifyCode(num);
for (int i = 0; i < num; i++) {
font = new Font("微软雅黑", Font.BOLD, r.nextInt(1, 40));
g.setFont(font);
g.setColor(new Color(r.nextInt(0, 256), r.nextInt(0, 256), r.nextInt(0, 256), r.nextInt(20, 180)));
g.drawString(String.valueOf(str.charAt(i)), r.nextInt(0, w), r.nextInt(0, h));
}
}
public static void addLineDisturbance(int num, Graphics2D g, int w, int h) {
Random r = new Random();
for (int i = 0; i < 5; i++) {
g.setStroke(new BasicStroke(r.nextInt(1, 5)));
g.drawLine(r.nextInt(0, w), r.nextInt(0, h), r.nextInt(0, w), r.nextInt(0, h));
}
}
}