public static void main(String[] args) throws IOException{
String code = generateCode(6);
System.out.println(code);
int width = 200;
int height = 50;
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = (Graphics2D) img.getGraphics();
//设置背景色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
//设置干扰线
for (int i = 10; i-- >0;) {
g.setColor(new Color(randomAB(0, 0xfffffff)));
//g.setColor(Color.RED);
g.drawArc(randomAB(0, width), randomAB(0, height), randomAB(0, width), randomAB(0, height), randomAB(0, 360), randomAB(0, 360));
}
Font f = new Font("黑体",Font.BOLD,50);
g.setColor(new Color(randomAB(0, 0xfffffff)));
//把文字绘制到居中
TextLayout layout = new TextLayout(code,f,g.getFontRenderContext());
Rectangle2D bounds = layout.getBounds();
int x = (int)(width-bounds.getWidth())/2;
int y = (int)(height - bounds.getHeight())/2;
g.drawString(code, (int)(x-bounds.getX()), (int)(y-bounds.getY()));
ImageIO.write(img, "png", new File("D:/1.png"));
}
/**
* 随机生成验证码字符串
* @param n
* @return
*/
public static String generateCode(int n){
final String codes = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjklmnpqrstuvwxyz23456789";
char[] cs = new char[n];
for(int i = n; i-->0;){
cs[i] = codes.charAt(randomAB(0, codes.length()));
}
return new String(cs);
}
/**
* 随机生成a-b之间的数
* @param a
* @param b
* @return
*/
public static int randomAB(int a,int b){
return (int)(Math.random()*Math.abs(a-b))+Math.min(a,b);
}
随机生成图片验证码
最新推荐文章于 2020-08-07 09:58:57 发布