一步一步实现 图片滑动验证码
项目中要使用 图片滑动验证码,顾了解之
需要以下几步来完成:
-
1.后端随机计算抠图的距离,生成背景与拼图块的图片,缓存 拼图块需 滑动的距离像素。
-
2.前端加载背景图 和 浮动框,通过拖动条拖动,后台进行验证。
项目需求,满足PC和移动Web调用:
-
此时要考虑PC和不同移动设备Web端的图形大小,防止变形。
-
参考【小红书】的滑块验证
-
后端生成 600* 300的背景图,浮动层 90*300。 它的浮动层模板 高度是和原图一致的,可省去计算高度的过程。
-
PC端缩放如: 400 *200,
-
移动端:288*144、 300 * 150
生成背景和滑动块的工具类:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Transparency;
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;
import javax.imageio.ImageIO;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.util.Base64Utils;
public class VerifyImageUtil {
private final static Logger log = LogManager.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";
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();
Random random = new Random();
int widthRandom = random.nextInt(oriImageWidth - 2 * templateWidth) + templateWidth;
int heightRandom = 0;
BufferedImage newImage = new BufferedImage(templateWidth, templateHeight, imageTemplate.getType());
Graphics2D graphics = newImage.createGraphics();
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);
byte[] newImagebyte = newImageOs.toByteArray();
ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream();
ImageIO.write(oriImage, IMG_FILE_TYPE, oriImagesOs);
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;
}
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++) {
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);
}
}
}
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();
}
}
在项目resource的目录存放背景图和浮动层模板:
public List<String> queryFileList(String path) {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
List<String> filelist = new ArrayList<String>();
try {
Resource[] resources = resolver.getResources(path);
for (Resource resource : resources) {
filelist.add(resource.getFile().getPath());
}
} catch (Exception e) {
e.printStackTrace();
}
return filelist;
}
@RequestMapping(value = "/getImageVerify", method = RequestMethod.GET)
public AjaxResult getImageVerifyCode(HttpServletRequest request) {
String IMG_PATH = "/image/bg/*.*";
String TEMP_IMG_PATH = "/image/fg/*.*";
List<String> imgList = queryFileList(IMG_PATH);
int randNum = new Random().nextInt(imgList.size());
File targetFile = new File(imgList.get(randNum));
List<String> tempimgList = queryFileList(TEMP_IMG_PATH);
randNum = new Random().nextInt(tempimgList.size());
File tempImgFile = new File(tempimgList.get(randNum));
Map<String, Object> resultMap = null;
try {
resultMap = VerifyImageUtil.pictureTemplatesCut(tempImgFile, targetFile);
int xWidth = (int) resultMap.get("xWidth");
request.setAttribute("xWidth",xWidth);
resultMap.remove("xWidth");
return AjaxResult.success(resultMap);
} catch (Exception e) {
return AjaxResult.error("获取验证码失败");
}
}
@RequestMapping(value = "/verifyImageCode", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
public AjaxResult verifyImageCode(@RequestParam(value = "moveLength") String moveLength, HttpServletRequest request) {
Double dMoveLength = Double.valueOf(moveLength);
AjaxResult resultMap;
try {
int xWidth = request.getAttribute("xWidth");
if (xWidth < 1) {
resultMap = AjaxResult.error("验证过期,请重试");
} else {
if (Math.abs((int) xWidth - dMoveLength) > 10) {
resultMap = AjaxResult.error("验证不通过");
} else {
resultMap = AjaxResult.success("验证通过");
}
}
} catch (Exception e) {
resultMap = AjaxResult.success("验证失败,请重试");
}
return resultMap;
}
我的前端vue实现,先看效果:
vue组件:
<template>
<div class="slide-verify" id="slideVerify" :style="widthlable" onselectstart="return false;">
<canvas :width="w" :height="h" ref="canvas" ></canvas>
<canvas :width="w" :height="h" ref="block" class="slide-verify-block"></canvas>
<div @click="refresh" class="slide-verify-refresh-icon"></div>
<div class="slide-verify-slider" :style="widthlable" :class="{'container-active': containerActive, 'container-success': containerSuccess, 'container-fail': containerFail}">
<div class="slide-verify-slider-mask" :style="{width: sliderMaskWidth}">
<div @mousedown="sliderDown"
@touchstart="touchStartEvent"
@touchmove="touchMoveEvent"
@touchend="touchEndEvent"
class="slide-verify-slider-mask-item"
:style="{left: sliderLeft}">
<div class="slide-verify-slider-mask-item-icon"></div>
</div>
</div>
<span class="slide-verify-slider-text">{{sliderText}}</span>
</div>
</div>
</template>
<script>
const PI = Math.PI;
function sum(x, y) {
return x + y
}
function square(x) {
return x * x
}
export default {
name: 'SlideVerify',
props: {
l: {
type: Number,
default: 42,
},
r: {
type: Number,
default: 10,
},
w: {
type: Number,
default: 310,
},
h: {
type: Number,
default: 155,
},
block_x: {
type: Number,
default: 155,
},
block_y: {
type: Number,
default: 20,
},
imgurl: {
type: String,
default: '',
},
miniimgurl: {
type: String,
default: '',
},
},
data() {
return {
containerActive: false,
containerSuccess: false,
containerFail: false,
canvasCtx: null,
blockCtx: null,
block: null,
canvasStr: null,
L: this.l + this.r * 2 + 3,
img: undefined,
originX: undefined,
originY: undefined,
isMouseDown: false,
trail: [],
widthlable:'',
sliderLeft: 0,
sliderMaskWidth: 0,
sliderText:'向右划'
}
},
mounted() {
this.init()
},
methods: {
init() {
this.initDom()
this.bindEvents()
this.widthlable ='width:'+this.w+'px;'
},
initDom() {
this.block = this.$refs.block;
this.canvasStr = this.$refs.canvas;
this.canvasCtx = this.canvasStr.getContext('2d')
this.blockCtx = this.block.getContext('2d')
},
initImg(h) {
var that = this
const img = document.createElement('img');
img.onload = onload;
img.onerror = () => {
img.src = that.imgurl
}
img.src = that.imgurl
img.onload = function(){
that.canvasCtx.drawImage(img, 0, 0, that.w, that.h)
}
this.img=img
const img1 = document.createElement('img');
var blockCtx = that.blockCtx
var block_y = h||that.block_y
img1.onerror = () => {
img1.src = that.miniimgurl
}
img1.src = that.miniimgurl
img1.onload = function(){
blockCtx.drawImage(img1, 0, block_y, 60, that.h)
}
},
refresh() {
this.$emit('refresh')
},
sliderDown(event) {
this.originX = event.clientX;
this.originY = event.clientY;
this.isMouseDown = true;
},
touchStartEvent(e) {
this.originX = e.changedTouches[0].pageX;
this.originY = e.changedTouches[0].pageY;
this.isMouseDown = true;
},
bindEvents() {
document.addEventListener('mousemove', (e) => {
if (!this.isMouseDown) return false;
const moveX = e.clientX - this.originX;
const moveY = e.clientY - this.originY;
if (moveX < 0 || moveX + 38 >= this.w) return false;
this.sliderLeft = moveX + 'px';
let blockLeft = (this.w - 40 - 20) / (this.w - 40) * moveX;
this.block.style.left = blockLeft + 'px';
this.containerActive = true;
this.sliderMaskWidth = moveX + 'px';
this.trail.push(moveY);
});
document.addEventListener('mouseup', (e) => {
if (!this.isMouseDown) return false
this.isMouseDown = false
if (e.clientX === this.originX) return false;
this.containerActive = false;
this.verify()
})
},
touchMoveEvent(e) {
if (!this.isMouseDown) return false;
const moveX = e.changedTouches[0].pageX - this.originX;
const moveY = e.changedTouches[0].pageY - this.originY;
if (moveX < 0 || moveX + 38 >= this.w) return false;
this.sliderLeft = moveX + 'px';
let blockLeft = (this.w - 40 - 20) / (this.w - 40) * moveX;
this.block.style.left = blockLeft + 'px';
this.containerActive = true;
this.sliderMaskWidth = moveX + 'px';
this.trail.push(moveY);
},
touchEndEvent(e) {
if (!this.isMouseDown) return false
this.isMouseDown = false
if (e.changedTouches[0].pageX === this.originX) return false;
this.containerActive = false;
this.verify()
},
verify() {
const arr = this.trail
const average = arr.reduce(sum) / arr.length
const deviations = arr.map(x => x - average)
const stddev = Math.sqrt(deviations.map(square).reduce(sum) / arr.length)
const left = parseInt(this.block.style.left)
this.$emit('success',left)
},
reset(h) {
this.containerActive = false;
this.containerSuccess = false;
this.containerFail = false;
this.sliderLeft = 0;
this.block.style.left = 0;
this.sliderMaskWidth = 0;
this.canvasCtx.clearRect(0, 0, this.w, this.h)
this.blockCtx.clearRect(0, 0, this.w,this.h)
this.initImg(h)
}
}
}
</script>
<style scoped>
.slide-verify {
position: relative;
width: 310px;
}
.slide-verify-block {
position: absolute;
left: 0;
top: 0
}
.slide-verify-refresh-icon {
position: absolute;
right: 0;
top: 0;
width: 34px;
height: 34px;
cursor: pointer;
background: url(https://cstaticdun.126.net//2.13.6/images/icon_light.4353d81.png) 0 -233px;
background-size: 32px 544px;
}
.slide-verify-slider {
position: relative;
text-align: center;
width: 310px;
height: 40px;
line-height: 40px;
margin-top: 15px;
background: #f7f9fa;
color: #45494c;
border: 1px solid #e4e7eb
}
.slide-verify-slider-mask {
position: absolute;
left: 0;
top: 0;
height: 40px;
border: 0 solid #1991FA;
background: #D1E9FE
}
.slide-verify-slider-mask-item {
position: absolute;
top: 0;
left: 0;
width: 40px;
height: 40px;
background: #fff;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
cursor: pointer;
transition: background .2s linear
}
.slide-verify-slider-mask-item:hover {
background: #1991FA
}
.slide-verify-slider-mask-item:hover .slide-verify-slider-mask-item-icon {
background-position: 0 -13px
}
.slide-verify-slider-mask-item-icon {
position: absolute;
top: 15px;
left: 13px;
width: 14px;
height: 12px;
background: url("../../assets/images/light.svg") 0 -26px;
background-size: 34px 471px
}
.container-active .slide-verify-slider-mask-item {
height: 38px;
top: -1px;
border: 1px solid #1991FA;
}
.container-active .slide-verify-slider-mask {
height: 38px;
border-width: 1px;
}
.container-success .slide-verify-slider-mask-item {
height: 38px;
top: -1px;
border: 1px solid #52CCBA;
background-color: #52CCBA !important;
}
.container-success .slide-verify-slider-mask {
height: 38px;
border: 1px solid #52CCBA;
background-color: #D2F4EF;
}
.container-success .slide-verify-slider-mask-item-icon {
background-position: 0 0 !important;
}
.container-fail .slide-verify-slider-mask-item {
height: 38px;
top: -1px;
border: 1px solid #f57a7a;
background-color: #f57a7a !important;
}
.container-fail .slide-verify-slider-mask {
height: 38px;
border: 1px solid #f57a7a;
background-color: #fce1e1;
}
.container-fail .slide-verify-slider-mask-item-icon {
top: 14px;
background-position: 0 -82px !important;
}
.container-active .slide-verify-slider-text,
.container-success .slide-verify-slider-text,
.container-fail .slide-verify-slider-text {
display: none;
}
</style>
使用:
<slideverify :l="42" ref="dialogopen"
:r="10"
:w="400"
:h="200"
:block_y="block_y"
:imgurl="imgurl"
:miniimgurl="miniimgurl"
@success="onSuccess"
@refresh="onRefresh"
:slider-text="text"
></slideverify>
methods: {
//获取验证码
getImageVerifyCode: function () {
var that = this
getImageVerifyCodeImg().then(res => {
if (!res || res.code != '200') {
this.$message({
showClose: true,
message: '获取图形验证码失败,请重试',
type: 'error'
})
} else {
var imgobj = res.data
that.block_y = imgobj.yHeight
that.imgurl = 'data:image/jpg;base64,' + imgobj.bigImage
that.miniimgurl = 'data:image/jpg;base64,' + imgobj.smallImage
}
})
},
//刷新
onRefresh() {
this.imgurl = ''
this.miniimgurl = ''
this.getImageVerifyCode()
},
//滑动结束,后台验证, l是滑动距离
onSuccess(l) {
verifyImageCode(l).then(res => {
if (res.msg === "验证通过") {
Message({
message: res.msg,
type: 'success'
})
} else {
Message({
message: res.msg,
type: 'error'
})
this.onRefresh();
}
})
}
}
移动端:uni-app插件市场
图片滑动验证码
根据后台返回内容,稍加修改,效果如图:
后台抠图所需的模板图:
更多模板图从【小红书】抓取下载。
小红书滑动块验证
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)