JAVA 模板抠图生成滑块拼图验证码原理及实现

实现效果图:

 

滑块验证码原理
很多网站使用滑块验证码提高网站安全性,为了做到真正的验证,必须要走后台服务器。
下面是java实现滑块验证的核心步骤:

1.从服务器随机取一张底透明有形状的模板图,再随机取一张背景图
2.根据模板小图和背景大图得到宽高,计算可控区域,随机在背景大图找到坐标抠图
3.根据步骤二的坐标点,对背景大图的抠图区域的颜色进行处理,根据模板的像素RGB值(透明RGB颜色值是0,有颜色的部分<0)对新生成的模板小图颜色赋值,背景大图生成遮罩层。
4.完成以上步骤之后得到两张图(扣下来的方块图,带有抠图区域阴影的原图),将这两张图和抠图区域的y坐标传到前台,x坐标存入session或者redis。
5.请求验证的步骤:前端向后台发起请求,后台随机一张图片做处理将处理完的两张图片的base64,抠图y坐标返回给前端。
6.前端在移动拼图时将滑动距离x坐标参数请求后台验证,服务器根据redis取出x坐标与参数的x进行比较,如果在伐值内则验证通过,否则清除x记录,重新刷新。

滑块验证码实现

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 滑块验证工具类
 * @author: zhoujin
 * @Date: Created in 10:57 2019/7/04
 * @Modified By:
 */
public class VerifyImageUtil {

    private static Logger log = LoggerFactory.getLogger(VerifyImageUtil.class);
    private static int BOLD = 5;
    private static final String IMG_FILE_TYPE = "jpg";
    private static final String TEMP_IMG_FILE_TYPE = "png";

    /**
     * 根据模板切图
     * @param templateFile
     * @param targetFile
     * @return
     * @throws Exception
     */
    public static Map<String, Object> pictureTemplatesCut(File templateFile, File targetFile) throws Exception {
        Map<String, Object> pictureMap = new HashMap<>();
        // 模板图
        BufferedImage imageTemplate = ImageIO.read(templateFile);
        int templateWidth = imageTemplate.getWidth();
        int templateHeight = imageTemplate.getHeight();

        // 原图
        BufferedImage oriImage = ImageIO.read(targetFile);
        int oriImageWidth = oriImage.getWidth();
        int oriImageHeight = oriImage.getHeight();

        //随机生成抠图坐标X,Y
        //X轴距离右端targetWidth  Y轴距离底部targetHeight以上
        Random random = new Random();
        int widthRandom = random.nextInt(oriImageWidth - 2*templateWidth) + templateWidth;
        int heightRandom = random.nextInt(oriImageHeight - templateHeight);
        log.info("原图大小{} x {},随机生成的坐标 X,Y 为({},{})", oriImageWidth,oriImageHeight,widthRandom,heightRandom);

        // 新建一个和模板一样大小的图像,TYPE_4BYTE_ABGR表示具有8位RGBA颜色分量的图像,正常取imageTemplate.getType()
        BufferedImage newImage = new BufferedImage(templateWidth, templateHeight, imageTemplate.getType());
        //得到画笔对象
        Graphics2D graphics = newImage.createGraphics();
        //如果需要生成RGB格式,需要做如下配置,Transparency 设置透明
        newImage = graphics.getDeviceConfiguration().createCompatibleImage(templateWidth, templateHeight, Transparency.TRANSLUCENT);

        // 新建的图像根据模板颜色赋值,源图生成遮罩
        cutByTemplate(oriImage,imageTemplate,newImage,widthRandom,heightRandom);

        // 设置“抗锯齿”的属性
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setStroke(new BasicStroke(BOLD, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
        graphics.drawImage(newImage, 0, 0, null);
        graphics.dispose();

        ByteArrayOutputStream newImageOs = new ByteArrayOutputStream();//新建流。
        ImageIO.write(newImage, TEMP_IMG_FILE_TYPE, newImageOs);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。
        byte[] newImagebyte = newImageOs.toByteArray();

        ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream();//新建流。
        ImageIO.write(oriImage, IMG_FILE_TYPE, oriImagesOs);//利用ImageIO类提供的write方法,将bi以jpg图片的数据模式写入流。
        byte[] oriImageByte = oriImagesOs.toByteArray();

        pictureMap.put("smallImage", Base64Utils.encodeToString(newImagebyte));
        pictureMap.put("bigImage", Base64Utils.encodeToString(oriImageByte));
        pictureMap.put("xWidth",widthRandom);
        pictureMap.put("yHeight",heightRandom);
        return pictureMap;
    }

    /**
     * 添加水印
     * @param oriImage
     */
    /*private static BufferedImage addWatermark(BufferedImage oriImage) throws IOException {
        Graphics2D graphics2D = oriImage.createGraphics();
        graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        // 设置水印文字颜色
        graphics2D.setColor(Color.BLUE);
        // 设置水印文字Font
        graphics2D.setFont(new java.awt.Font("宋体", java.awt.Font.BOLD, 50));
        // 设置水印文字透明度
        graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
        // 第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
        graphics2D.drawString("zhoujin@qq.com", 400,300);
        graphics2D.dispose(); //释放
        return oriImage;
    }*/

    /**
     * @param oriImage  原图
     * @param templateImage  模板图
     * @param newImage  新抠出的小图
     * @param x         随机扣取坐标X
     * @param y         随机扣取坐标y
     * @throws Exception
     */
    private static void cutByTemplate(BufferedImage oriImage, BufferedImage templateImage,BufferedImage newImage, int x, int y){
        //临时数组遍历用于高斯模糊存周边像素值
        int[][] martrix = new int[3][3];
        int[] values = new int[9];

        int xLength = templateImage.getWidth();
        int yLength = templateImage.getHeight();
        // 模板图像宽度
        for (int i = 0; i < xLength; i++) {
            // 模板图片高度
            for (int j = 0; j < yLength; j++) {
                // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
                int rgb = templateImage.getRGB(i, j);
                if (rgb < 0) {
                    newImage.setRGB(i, j,oriImage.getRGB(x + i, y + j));

                    //抠图区域高斯模糊
                    readPixel(oriImage, x + i, y + j, values);
                    fillMatrix(martrix, values);
                    oriImage.setRGB(x + i, y + j, avgMatrix(martrix));
                }

                //防止数组越界判断
                if(i == (xLength-1) || j == (yLength-1)){
                    continue;
                }
                int rightRgb = templateImage.getRGB(i + 1, j);
                int downRgb = templateImage.getRGB(i, j + 1);
                //描边处理,,取带像素和无像素的界点,判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
                if((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0)){
                    newImage.setRGB(i, j, Color.white.getRGB());
                    oriImage.setRGB(x + i, y + j,Color.white.getRGB());
                }
            }
        }
    }

    private static void readPixel(BufferedImage img, int x, int y, int[] pixels) {
        int xStart = x - 1;
        int yStart = y - 1;
        int current = 0;
        for (int i = xStart; i < 3 + xStart; i++)
            for (int j = yStart; j < 3 + yStart; j++) {
                int tx = i;
                if (tx < 0) {
                    tx = -tx;

                } else if (tx >= img.getWidth()) {
                    tx = x;
                }
                int ty = j;
                if (ty < 0) {
                    ty = -ty;
                } else if (ty >= img.getHeight()) {
                    ty = y;
                }
                pixels[current++] = img.getRGB(tx, ty);

            }
    }

    private static void fillMatrix(int[][] matrix, int[] values) {
        int filled = 0;
        for (int i = 0; i < matrix.length; i++) {
            int[] x = matrix[i];
            for (int j = 0; j < x.length; j++) {
                x[j] = values[filled++];
            }
        }
    }

    private static int avgMatrix(int[][] matrix) {
        int r = 0;
        int g = 0;
        int b = 0;
        for (int i = 0; i < matrix.length; i++) {
            int[] x = matrix[i];
            for (int j = 0; j < x.length; j++) {
                if (j == 1) {
                    continue;
                }
                Color c = new Color(x[j]);
                r += c.getRed();
                g += c.getGreen();
                b += c.getBlue();
            }
        }
        return new Color(r / 8, g / 8, b / 8).getRGB();
    }
}

 

控制层代码及校验实现

   private static final String IMG_PATH = "/image";

    private static final String TEMP_IMG_PATH = "/templateImg/template.png";

    private static final Long IMG_CACHE_EX_TIME = 120L;


    /**
     * @param @return 参数说明
     * @return BaseRestResult 返回类型
     * @Description: 生成滑块拼图验证码
     */
    @RequestMapping(value = "/getImageVerifyCode.do", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public BaseRestResult getImageVerifyCode() throws Exception {
        //读取图库目录
        File imgCatalog = new File(getClass().getResource(IMG_PATH).getPath());
        File[] files = imgCatalog.listFiles();

        int randNum = new Random().nextInt(files.length);
        File targetFile = files[randNum];
        File tempImgFile = new File(getClass().getResource(TEMP_IMG_PATH).getPath());

        //根据模板裁剪图片
        Map<String, Object> resultMap = VerifyImageUtil.pictureTemplatesCut(tempImgFile,targetFile);
        int xWidth = (int) resultMap.get("xWidth");
        //sessionId 为key,value滑动距离X轴,缓存120秒
        redisCacheHelper.set(session.getId(),xWidth,IMG_CACHE_EX_TIME);

        //移除map的滑动距离,不返回给前端
        resultMap.remove("xWidth");
        resultMap.put(ApiConstants.ERR_CODE, ApiConstants.SUCCESS_CODE_0);
        resultMap.put(ApiConstants.ERR_MSG,ApiConstants.SUCCESS_MSG);
        return new BaseRestResult(resultMap);
    }


 /**
     * 校验滑块拼图验证码
     *
     * @param moveLength 移动距离
     * @return BaseRestResult 返回类型
     * @Description: 生成图形验证码
     */
    @RequestMapping(value = "/verifyImageCode.do", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public BaseRestResult verifyImageCode(@RequestParam(value = "moveLength") String moveLength) {
        Double dMoveLength = Double.valueOf(moveLength);
        Map<String, Object> resultMap = new HashMap<>();
        try {
            Object xWidth = redisCacheHelper.get(session.getId());
            if (xWidth == null) {
                resultMap.put("errcode", 1);
                resultMap.put("errmsg", "验证过期,请重试");
                return new BaseRestResult(resultMap);
            }
            ;
            if (Math.abs((int) xWidth - dMoveLength) > 10) {
                resultMap.put("errcode", 1);
                resultMap.put("errmsg", "验证不通过");
            } else {
                resultMap.put("errcode", 0);
                resultMap.put("errmsg", "验证通过");
            }
        } catch (Exception e) {
            throw new EsServiceException(e.getMessage());
        } finally {
            redisCacheHelper.del("xWidth");
        }
        return new BaseRestResult(resultMap);
    }

前端显示图片


<img src="https://img-blog.csdnimg.cn/2022010701052042530.png" alt="抠图">
<img src="https://img-blog.csdnimg.cn/2022010701052125869.jpeg" alt="带抠图阴影的背景">

至此,模板实现滑块拼图验证码完整代码已贴上,经测试,生成验证码请求时间78ms还算挺快!

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值