第一种:
public static void main(String[] args) throws IOException { BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_BGR); //获取画笔 Graphics2D g = (Graphics2D) image.getGraphics(); //设置图片背景颜色 g.setColor(Color.BLACK); g.fillRect(0,0,80,20); //写数据 g.setColor(Color.CYAN); //设置字体 g.setFont(new Font(null,Font.BOLD,20)); g.drawString(makeNum(),0,20); //设置所生成图片的输出路径 ImageIO.write(image,"png",new File("D:\\验证码.png")); } //生成随机数 private static String makeNum(){ Random random = new Random(); String num=random.nextInt(999999)+""; StringBuffer stringBuffer = new StringBuffer(); for (int i = 0; i < 7-num.length(); i++) { stringBuffer.append("0"); } num=stringBuffer+num; return num; }
结果:
第二种:
public class MakeVerificationCode { static Random random = new Random(); //验证码宽高 static int width=100; static int height=50; public static void main(String[] args) { //创建图片缓存区,传参为宽高和图片类型 BufferedImage imageBuffer = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics g = init(imageBuffer);//得到画笔 drawBackgroundPane(g);//画一个彩色背景 drawcode(g);//画验证字符 drawLine(g);//画干扰线 saveCode(imageBuffer);//保存验证码图片 } //获取随机颜色 private static Color getRandomColor() { return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)); } //获取随机字符 private static String getRandomString() { char[] StringLibrary = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM".toCharArray();//验证码字符字典 int index;//随机坐标 String showString = ""; for(int i= 0;i<4;i++) {//四个随机验证字符,四次循环 index = random.nextInt(StringLibrary.length); showString += String.valueOf(StringLibrary[index]); } return showString; } //保存验证码为图片 private static void saveCode(BufferedImage imageBuffer) { try { ImageIO.write(imageBuffer, "png", new FileOutputStream(new File("D:\\验证码.png")));//这里要将图片保存路径改成你的,建议用相对路径 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //画干扰线 private static void drawLine(Graphics g) { g.setColor(new Color(0,0,0));//黑色线 for(int i =0;i<30;i++) { int x1 = random.nextInt(width); int x2 = random.nextInt(width); int y1 = random.nextInt(height); int y2 = random.nextInt(height); g.drawLine(x1, y1, x2, y2); } } // 初始化画笔 private static Graphics init(BufferedImage imageBuffer) { // 获取画笔 Graphics g = imageBuffer.getGraphics();// 获取画笔 g.setFont(new Font(Font.MONOSPACED, Font.BOLD, 35));// 设置字体 return g; } // 画彩色背景 private static void drawBackgroundPane(Graphics g) { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { g.setColor(getRandomColor());//随机画笔颜色 g.fillRect(i, j, 1, 1); } } } //画验证码字符 private static void drawcode(Graphics g) { String code = getRandomString(); g.setColor(new Color(0,0,0));//设置画笔颜色 g.drawString(code, width/10, height/4*3); } }
结果:
这个方法是别人的(这个是他的地址):http://t.csdn.cn/Mu6iX
完结撒花!!!