java生成随机验证码
一直想自己实现一下,所以就动手做了一下,当然,也有很多不足之处,请大佬指点。
package Shuju;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Shencheng {
public static void main(String args[]) throws IOException {
int w = 200;
int h = 60;
String code = zf(5);
BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(Color.white);
g.fillRect(0,0,w,h);
for(int i=100;i-->0;){
g.setColor(new Color(rand(0,0xffffff)));
g.drawArc(rand(0,w),rand(0,h),rand(0,w),rand(0,h),rand(0,360),rand(0,360));
}
Font f = new Font("黑体",Font.BOLD,30);
g.setColor(new Color(rand(0,0xffffff)));
g.setFont(f);
TextLayout layout = new TextLayout(code,f,g.getFontRenderContext());
Rectangle2D bounds = layout.getBounds();
int x = (int)(w-bounds.getWidth())/2;
int y = (int)(h-bounds.getHeight())/2;;
g.drawString(code,(int)(x-bounds.getX()),(int)(y-bounds.getY()));
ImageIO.write(image,"png",new File("C:\\Users\\Java\\src\\验证码生成\\生成图片\\2.jpg"));
}
//1.随机生成验证码字符串
//2.创建图片
//3.背景色
//4.添加干扰线
//5.绘制字符到图片
//6.扭曲混淆处理
//7.输出
private static String zf(int n){
String zf = "abcdefg345678hTUVWX89YZ01234567RSTUV8TUVWX89YZ9";
char [] ch = new char[n];
for(int i=n;i-->0;){
ch[i] = zf.charAt(rand(0,zf.length()));
}
System.out.println(ch);
return new String(ch);
}
private static int rand(int a, int b){
return (int)(Math.random()*Math.abs(a-b)+Math.min(a,b));
}
}