实现效果:
ImageUtil类:
public class ImageUtils { private static int width=150; private static int height=50; private static int codeCount=6; private static Random rand=new Random(); //随机生成的6位大小字母 小写字母 数字的组合 private static String generateCode() { String code=""; char[] codes=new char[62]; int count=0; //把所有小写字母放入数组 for(int i='a';i<='z';i++) { codes[count]=(char)i; count++; } //把所有大写字母放入数组 for(int i='A';i<='Z';i++) { codes[count]=(char)i; count++; } //把所有数字放入数组 for(int i='0';i<='9';i++) { codes[count]=(char)i; count++; } for(int i=0;i<codeCount;i++) { //随机从数组中取一个字符并放到字符串中 code+=codes[rand.nextInt(codes.length)]; } return code; } public static BufferedImage getImage() { BufferedImage bi=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics g=bi.getGraphics(); //把背景填充成白色 g.fillRect(0, 0, width, height); String code=generateCode(); int x=0; for(int i=0;i<code.length();i++) { char c=code.charAt(i); //随机设置字体的大小 g.setFont(new Font("黑体",Font.BOLD,20+rand.nextInt(25))); //随机设置字体的颜色 g.setColor(new Color(rand.nextInt(256),rand.nextInt(256),rand.nextInt(256))); g.drawString(String.valueOf(c),x,height-10); x+=width/codeCount; } //生成干扰线 for(int i=0;i<10;i++) { g.setColor(new Color(rand.nextInt(256),rand.nextInt(256),rand.nextInt(256))); int x1=rand.nextInt(width); int y1=rand.nextInt(height); int x2=rand.nextInt(width); int y2=rand.nextInt(height); g.drawLine(x1, y1, x2, y2); } return bi; } }
测试类:
public class Test { public static void main(String[] args) { File file=new File("e:/mydata/code.jpg"); try { //把生成的验证码图片写到文件中 ImageIO.write(ImageUtils.getImage(), "jpg", file); } catch (IOException e) { e.printStackTrace(); } } }
0条评论
点击登录参与评论