本文实例讲述了java图片滑动验证(登录验证)原理与实现方法。分享给大家供大家参考,具体如下:
这是我简单做出的效果图,处理300 x150px的校验图,并把图片发到前端,用时50毫秒左右,速度还是非常快的。
,
1。利用java从大图中随机抠出一张小图,并在大图上给抠出小图的位置加阴影,然后把这两张图片返回给前端;
2。前端获取图片,用户滑动小图到阴影的位置,获取小图滑动的距离,返回给java后台进行校验;
3。校验通过,返回校验通过编号;
4。前端调登录接口,把账号:密码,和校验编号传到Java后台进行登录。
1。计算需要的小图轮廓,用二维数组来表示,二维数组有两张值,0和1,其中0表示没有颜色,1有颜色,如下图,我要抠图的轮廓是这样的:
左边和下边有有半圆,这个根据圆的公式就可以了,代码示例:
静态int targetLength=55;//小图长 静态int targetWidth=45;//小图宽 静态int圆=6;//半径 静态int r1=3;//距离点/* * * * @Createdate: 2019年1月24日上午10:52:42 * @Title: getBlockData * @Description:生成小图轮廓 * @author mzl * @return int [] [] * @throws */私有静态int [] [] getBlockData () { int [] [] data=https://www.yisu.com/zixun/new int [targetLength] [targetWidth]; 双x2=targetLength-circleR;//随机生成圆的位置 双h2=圆+ math . random () * (targetWidth-3 * circleR-r1); 双博=圆*圆; 双xbegin=targetLength-circleR-r1; 双ybegin=targetWidth-circleR-r1; for (int i=0;我=xbegin & & d3>=po)) { 数据[我][j]=0; 其他}{ 数据[我][j]=1; } } } 返回数据; } >之前 2。根据计算处理的小图轮廓,在大图上抠图
/* * * * @Createdate: 2019年1月24日上午10:51:30 * @Title: cutByTemplate * @Description:生成小图片,给大图片添加阴影 * @author mzl * @param oriImage * @param targetImage * @param templateImage * @param x * @param y无效 * @throws */私有静态孔隙cutByTemplate (BufferedImage oriImage, BufferedImage targetImage, int [] [] templateImage, int x, int y) { for (int i=0;我& lt;targetLength;我+ +){ for (int j=0;j & lt;targetWidth;j + +) { int rgb=templateImage[我][j];//原图中对应位置变色处理 int rgb_ori=oriImage。getRGB (x + y + j); 如果(rgb==1) {//抠图上复制对应颜色值 targetImage。setRGB (i, j, rgb_ori);//原图对应位置颜色变化 oriImage。setRGB (x + y + j, rgb_ori,0 x363636); 其他}{//这里把背景设为透明 targetImage。setRGB (i, j rgb_ori,0 x00ffffff); } } } } >之前3。把大图小图转base64码,方便返回给前端
/* * * * @Createdate: 2019年1月24日上午11:49:42 * @Title: createImage * @Description:获取大图,小图Base64码 * @author mzl * @param url * @return Map<字符串,String> * @throws */公共静态Map<字符串,String>createImage(字符串url, int, int W, Map<字符串,String>resultMap) { 尝试{ BufferedImage BufferedImage=ImageIO。读(新FileInputStream (url)); BufferedImage目标=new BufferedImage (targetLength, targetWidth BufferedImage.TYPE_4BYTE_ABGR); cutByTemplate (bufferedImage目标,getBlockData (), L, W); resultMap。put (" b ", getImageBASE64 (bufferedImage));//大图 resultMap。把(“s”, getImageBASE64(目标));//小图 }捕捉(IOException e) { e.printStackTrace (); 最后}{ 返回resultMap; } }/* * * * @Createdate: 2019年1月24日上午11:14:19 * @Title: getImageStr * @Description:图片转BASE64 * @author mzl * @param形象 * @return * @throws IOException字符串 * @throws */公共静态字符串getImageBASE64 (BufferedImage图像)抛出IOException { ByteArrayOutputStream=新ByteArrayOutputStream (); ImageIO.write(形象,“png”); byte [] b=out.toByteArray();//转成字节数组 BASE64Encoder编码器=new BASE64Encoder (); 返回encoder.encode (b);//生成base64编码 }java图片滑动验证(登录验证)原理与实现方法详解