int width = 100; int height = 50; // 1.创建图片对象 BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR); //2.设置验证码背景色 和 边框色 Graphics g = img.getGraphics(); g.setColor(Color.PINK); g.fillRect(0,0,width,height); g.setColor(Color.BLUE); g.drawRect(0,0,width-1,height-1); //定义一个随机的源本 String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); for(int i = 1; i <= 4 ; i++){ int index = random.nextInt(str.length()); char c = str.charAt(index); System.out.print(c); //3.写入验证码字符串 g.drawString(c+"",width/5*i,height/2); } System.out.println(); //3.1 增加干扰线 for(int i = 0; i < 5; 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); } ImageIO.write(img,"jpg",response.getOutputStream());