当前位置: 首页 > 工具软件 > JCaptcha > 使用案例 >

JCaptcha生成验证码并读取

段干靖
2023-12-01

Maven配置

<dependency>

            <groupId>com.octo.captcha</groupId>

            <artifactId>jcaptcha</artifactId>

            <version>1.0</version>

        </dependency>

 

编写ImageCode验证码类

package com.bruce.portal.web.code;

import lombok.Data;

import javax.imageio.ImageIO;

import javax.imageio.stream.ImageOutputStream;

import java.awt.*;

import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.util.Random;

 

@Data

public class ImageCode {

private String code;

private ByteArrayInputStream byteArrayInputStream;

private int width =400;

private int height =100;

public static ImageCode getInstance() {

return new ImageCode();

}

private ImageCode() {

try {

BufferedImage bufferedImage =new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);

Graphics graphics =bufferedImage.getGraphics();

graphics.setColor(new Color(255,255,255));

graphics.fillRect(0,0,width,height);

graphics.setFont(new Font("宋体",Font.PLAIN,30));

Random random =new Random();

code ="";

=========================start 生成6位数字===========================

//            for (int i = 0; i < 6; i++) {

//                String s = String.valueOf(random.nextInt(10));

//                code += s;

//

//                graphics.setColor(new Color(0, 0, 0));

//                graphics.drawString(s, (width / 6) * i, 40);

//

//

//                //划线

//                graphics.setColor(new Color(100, 100, 100));

//                graphics.drawLine((width / 6) * i, 40, (width / 6) * i + 25, 40 - 30);

//            }

=========================end 生成6位数字===========================

            // =========================start 生成加减运算验证码==========================

            int num1 =random.nextInt(20);

int num2 =random.nextInt(20);

graphics.setColor(new Color(0,200,100));

graphics.drawString(num1 +"",2,60);

graphics.drawString("+", (width /6) *1 +2,60);

graphics.drawString(num2 +"", (width /6) *2 +2,60);

graphics.drawString("=", (width /6) *3 +2,60);

graphics.drawString("?", (width /6) *4 +2,60);

this.code = (num1 +num2) +"";

// =========================end 生成加减运算验证码==========================

            //画出干扰线

            for (int i =0; i <100; i++) {

int x =random.nextInt(width);

int y =random.nextInt(height);

int x1 =random.nextInt(20);

int y1 =random.nextInt(20);

graphics.drawLine(x,y,x +x1,y +y1);

}

graphics.dispose();

ByteArrayInputStream inputStream =null;

ByteArrayOutputStream outputStream =new ByteArrayOutputStream();

ImageOutputStream imageOutputStream =ImageIO.createImageOutputStream(outputStream);

ImageIO.write(bufferedImage,"jpeg",imageOutputStream);

inputStream =new ByteArrayInputStream(outputStream.toByteArray());

this.byteArrayInputStream = inputStream;

}catch (IOException e) {

e.printStackTrace();

System.out.println("生成验证码失败");

}

}

}

 

编写JCaptchaUtil工具类

package com.bruce.common.util;

import com.octo.captcha.CaptchaFactory;

import com.octo.captcha.component.image.backgroundgenerator.UniColorBackgroundGenerator;

import com.octo.captcha.component.image.color.RandomRangeColorGenerator;

import com.octo.captcha.component.image.fontgenerator.RandomFontGenerator;

import com.octo.captcha.component.image.textpaster.RandomTextPaster;

import com.octo.captcha.component.image.wordtoimage.ComposedWordToImage;

import com.octo.captcha.component.word.FileDictionary;

import com.octo.captcha.component.word.wordgenerator.ComposeDictionaryWordGenerator;

import com.octo.captcha.engine.GenericCaptchaEngine;

import com.octo.captcha.image.gimpy.GimpyFactory;

import com.octo.captcha.service.image.ImageCaptchaService;

import com.octo.captcha.service.multitype.GenericManageableCaptchaService;

public class JCaptchaUtil {

private static final ImageCaptchaService service =imageCaptchaService();

public static ImageCaptchaService getService() {

return service;

}

public static ImageCaptchaService imageCaptchaService() {

//设置背景

        UniColorBackgroundGenerator backgroundGenerator =new UniColorBackgroundGenerator(100,50);

//设置颜色

        RandomRangeColorGenerator textColor =new RandomRangeColorGenerator(new int[]{0,250},new int[]{0,250},new int[]{0,250});

RandomTextPaster randomTextPaster =new RandomTextPaster(4,5,textColor);

//设置字体

        RandomFontGenerator randomFontGenerator =new RandomFontGenerator(20,30);

//组装成图像

        ComposedWordToImage composedWordToImage =new ComposedWordToImage(randomFontGenerator,backgroundGenerator,randomTextPaster);

ComposeDictionaryWordGenerator cdwg =new ComposeDictionaryWordGenerator(new FileDictionary("toddlist"));

GimpyFactory gf =new GimpyFactory(cdwg,composedWordToImage);

GenericCaptchaEngine genericCaptchaEngine =new GenericCaptchaEngine(new CaptchaFactory[]{gf});

return new GenericManageableCaptchaService(genericCaptchaEngine,20,2000,2000);

}

}

 

编写JCaptchaController用于请求生成验证码

package com.bruce.portal.web.controller;

import com.bruce.common.util.JCaptchaUtil;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

@RestController

@RequestMapping("/jcaptcha")

public class JCaptchaController {

String attrName ="verifyCode";

@GetMapping("/generatorCode")

public void generatorCode(HttpServletRequest request,HttpServletResponse response) {

System.out.println("generatorCode");

try {

BufferedImage bufferedImage =JCaptchaUtil.getService().getImageChallengeForID(request.getSession().getId());

ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream();

//ImageIO jpegEncoder = JPEGCodec.createJPEGEncoder(byteArrayOutputStream);

            String formatName ="jpg";

//FileOutputStream out = new FileOutputStream(dstName);

//JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

//encoder.encode(dstImage);

            ImageIO.write(bufferedImage,formatName,byteArrayOutputStream);

response.setHeader("Cache-Control","no-store");

response.setContentType("image/jpeg");

byte[]bytes =byteArrayOutputStream.toByteArray();

ServletOutputStream servletOutputStream = response.getOutputStream();

servletOutputStream.write(bytes);

servletOutputStream.flush();

servletOutputStream.close();

}catch (IOException ioe) {

ioe.printStackTrace();

}

}

@GetMapping("/verify")

public String verify(String verifyCode,HttpServletRequest request) {

boolean flag =JCaptchaUtil.getService().validateResponseForID(request.getSession().getId(), verifyCode);

if (flag) {

return "验证码校验验通过";

}

return "验证码校验不通过";

}

}

 

 类似资料: