public class CaptchaService { private int width = 90; private int height = 20; private int codeLength = 6; private int xx =11; private int fontHeight = 18; private int codeY = 16; private char[] codes = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'}; public Map<String,Object> generateCodeAndPic() throws IOException { BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics gp = bufferedImage.getGraphics(); Random random = new Random(); gp.setColor(Color.WHITE);//图片背景:白色 gp.fillRect(0,0,width,height); Font font = new Font("黑体",Font.BOLD,fontHeight); gp.setFont(font); gp.setColor(Color.BLUE);//边框设置为蓝色 gp.drawRect(0,0,width - 1,height - 1); gp.setColor(Color.RED);//干扰线设置为红色 for(int i = 0;i < 20; i++){ int x = random.nextInt(width); int y = random.nextInt(height); int x1 = random.nextInt(15); int y1 = random.nextInt(15); gp.drawLine(x, y ,x + x1,y + y1); } StringBuffer randomCode = new StringBuffer(); int red = 0,green = 0,blue = 0; for (int i = 0;i<codeLength;i++){ String code = String.valueOf(codes[random.nextInt(36)]); red = random.nextInt(255); green = random.nextInt(255); blue = random.nextInt(255); gp.setColor(new Color(red,green,blue));//验证码颜色随机 gp.drawString(code,(i +1)* xx,codeY); randomCode.append(code); } Map<String,Object> map = new HashMap<>(); map.put("code",randomCode); map.put("codePic",bufferedImage); map.put("base64",convertToBase64(bufferedImage)); return map; } private String convertToBase64(BufferedImage image) throws IOException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); ImageIO.write(image,"jpg",stream); byte[] bytes = stream.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); String encode = encoder.encode(bytes); stream.close(); return encode; } /* public static void main(String[] args) throws IOException { OutputStream out = new FileOutputStream("F://img/" + System.currentTimeMillis()+".jpg"); CaptchaService c = new CaptchaService(); Map<String,Object> map = c.generateCodeAndPic(); ImageIO.write((RenderedImage) map.get("codePic"),"jpeg",out); System.out.println("验证码:"+map.get("code")); }*/ }