这篇文章主要介绍“Vue如何实现图片验证码生成”,在日常操作中,相信很多人在Vue如何实现图片验证码生成问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Vue如何实现图片验证码生成”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
前端逻辑大体就是进行图形绘制,取几个随机数放入图片中,加入干扰,进行验证
1.创建验证码组件identify.vue
<template> <div class="s-canvas" > <canvas id="s-canvas" :width="contentWidth" :height="contentHeight"></canvas> </div> </template> <script> export default{ name: 'SIdentify', props: { identifyCode: { // 默认注册码 type: String, default: '1234' }, fontSizeMin: { // 字体最小值 type: Number, default: 25 }, fontSizeMax: { // 字体最大值 type: Number, default: 35 }, backgroundColorMin: { // 验证码图片背景色最小值 type: Number, default: 200 }, backgroundColorMax: { // 验证码图片背景色最大值 type: Number, default: 220 }, dotColorMin: { // 背景干扰点最小值 type: Number, default: 60 }, dotColorMax: { // 背景干扰点最大值 type: Number, default: 120 }, contentWidth: { // 容器宽度 type: Number, default: 117 }, contentHeight: { // 容器高度 type: Number, default: 32 } }, methods: { // 生成一个随机数 randomNum (min, max) { return Math.floor(Math.random() * (max - min) + min) }, // 生成一个随机的颜色 randomColor (min, max) { let r = this.randomNum(min, max) let g = this.randomNum(min, max) let b = this.randomNum(min, max) return 'rgb(' + r + ',' + g + ',' + b + ')' }, drawPic () { let canvas = document.getElementById('s-canvas') let ctx = canvas.getContext('2d') ctx.textBaseline = 'bottom' // 绘制背景 ctx.fillStyle = '#e6ecfd' ctx.fillRect(0, 0, this.contentWidth, this.contentHeight) // 绘制文字 for (let i = 0; i < this.identifyCode.length; i++) { this.drawText(ctx, this.identifyCode[i], i) } this.drawLine(ctx) this.drawDot(ctx) }, drawText (ctx, txt, i) { ctx.fillStyle = this.randomColor(50, 160) // 随机生成字体颜色 ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei' // 随机生成字体大小 let x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1)) let y = this.randomNum(this.fontSizeMax, this.contentHeight - 5) var deg = this.randomNum(-30, 30) // 修改坐标原点和旋转角度 ctx.translate(x, y) ctx.rotate(deg * Math.PI / 180) ctx.fillText(txt, 0, 0) // 恢复坐标原点和旋转角度 ctx.rotate(-deg * Math.PI / 180) ctx.translate(-x, -y) }, drawLine (ctx) { // 绘制干扰线 for (let i = 0; i < 4; i++) { ctx.strokeStyle = this.randomColor(100, 200) ctx.beginPath() ctx.moveTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight)) ctx.lineTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight)) ctx.stroke() } }, drawDot (ctx) { // 绘制干扰点 for (let i = 0; i < 30; i++) { ctx.fillStyle = this.randomColor(0, 255) ctx.beginPath() ctx.arc(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight), 1, 0, 2 * Math.PI) ctx.fill() } } }, watch: { identifyCode () { this.drawPic() } }, mounted () { this.drawPic() } } </script>
2.父组件
前端生成验证码的校验是自己生成验证码,用户输入的值和生成的验证码字符串进行比对校验的,校验没有走后端,在真正发送请求到后端的时候也是不将验证码传给后台的。
<template> <div slot="content" class="reg-body"> <div class="main-content"> <el-form ref="form" :model="form" :rules="rules" label-width="125px" label-position="left"> <el-form-item label="验证码" class="my-item" prop="code"> <el-input v-model.trim="form.code" placeholder="请输入正确的验证码" size="small" /> <span class="login-code" > <Identify :identifyCode="identifyCode"></Identify> </span> <span class="el-icon-refresh-right" @click="refreshCode" /> </el-form-item> </el-form> <div > <el-button v-if="form.agreement" @click="submitForm()" :loading="loading" >提交</el-button> </div> </div> </div> </template> <script> import Identify from "./identify"; export default { name: "Reg", mixins: [region], components: {Identify }, data() { return { formSetting: { contentWidth: 340, }, form: { logoUrl: "", licenseUrl: "", description: [], account: "", name: "", }, code:this.$route.query.code, identifyCodes: "1234567890abcdefjhijklinopqrsduvwxyz", identifyCode: "", picList: [], props: { label: "name", value: "id", children: "children" }, rules: { code: [{ required: true, message: "请输入验证码", trigger: "change" }], }, formList: [], }; }, created() { // this.getAllDict() }, mounted() { this.getRegion(); // 初始化验证码 this.identifyCode = ""; this.makeCode(this.identifyCodes, 4); localStorage.setItem("code", this.code); }, methods: { openHtml() { this.visible = true; }, //刷新验证码 refreshCode() { this.identifyCode = ""; this.makeCode(this.identifyCodes, 4); }, //生成验证上的随机数,验证码中的数从identifyCodes中取, makeCode(o, l) { for (let i = 0; i < l; i++) { this.identifyCode += this.identifyCodes[ this.randomNum(0, this.identifyCodes.length) ]; } }, //生成随机数,这里是生成 //Math.random()方法返回大于等于0小于1的一个随机数 //随机数 = Math.floor(Math.random() * 可能的总数 + 第一个可能的值) randomNum(min, max) { return Math.floor(Math.random() * (max - min) + min); }, // 提交表单 submitForm() { this.$refs["form"].validate((valid) => { if (valid) { if (this.loading) { return; } this.loading = true; this.submit(); } else { return false; } }); }, submit: async function () { if (this.form.code.toLowerCase() !== this.identifyCode.toLowerCase()) { this.$msg({ type: "error", message: "请填写正确验证码" }); this.refreshCode(); this.loading = false; return; } else { //验证码校验成功就可以调接口提交表单了 }, }, }; </script>
后台思路很,利用BufferedImage类创建一张图片,再用Graphics对图片进行绘制(生成随机字符,添加噪点,干扰线)即可。
package com.hengtiansoft.gxrc.base.util; import com.hengtiansoft.gxrc.common.constant.MagicNumConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.imageio.ImageIO; import java.awt.Font; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.Random; @Slf4j @Component public class ImgCaptchaUtil { private Random random = new Random(); /** * 验证码的宽 */ private final int width = 160; /** * 验证码的高 */ private final int height = 40; /** * 验证码的干扰线数量 */ private final int lineSize = 30; /** * 验证码词典 */ private final String randomString = "0123456789abcdefghijklmnopqrstuvwxyz"; /** * 获取字体 * @return */ private Font getFont() { return new Font("Times New Roman", Font.ROMAN_BASELINE, MagicNumConstant.FORTY); } /** * 获取颜色 * @param fc * @param bc * @return */ private Color getRandomColor(int fc, int bc) { int fcc = Math.min(fc, MagicNumConstant.TWO_HUNDRED_FIFTY_FIVE); int bcc = Math.min(bc, MagicNumConstant.TWO_HUNDRED_FIFTY_FIVE); int r = fcc + random.nextInt(bcc - fcc - MagicNumConstant.SIXTEEN); int g = fcc + random.nextInt(bcc - fcc - MagicNumConstant.FOURTEEN); int b = fcc + random.nextInt(bcc - fcc - MagicNumConstant.TWELVE); return new Color(r, g, b); } /** * 绘制干扰线 * @param g */ private void drawLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(MagicNumConstant.TWENTY); int yl = random.nextInt(MagicNumConstant.TEN); g.drawLine(x, y, x + xl, y + yl); } /** * 获取随机字符 * @param num * @return */ private String getRandomString(int num) { int number = num > 0 ? num : randomString.length(); return String.valueOf(randomString.charAt(random.nextInt(number))); } /** * 绘制字符串 * @param g * @param randomStr * @param i * @return */ private String drawString(Graphics g, String randomStr, int i) { g.setFont(getFont()); g.setColor(getRandomColor(MagicNumConstant.ONE_HUNDRED_EIGHT, MagicNumConstant.ONE_HUNDRED_NINETY)); String rand = getRandomString(random.nextInt(randomString.length())); String randomString = randomStr + rand; g.translate(random.nextInt(MagicNumConstant.THREE), random.nextInt(MagicNumConstant.SIX)); g.drawString(rand, MagicNumConstant.FORTY * i + MagicNumConstant.TEN, MagicNumConstant.TWENTY_FIVE); return randomString; } /** * 生成随机图片,返回 base64 字符串 * @param * @return */ public Map<String, String> getImgCodeBaseCode(int length) { Map<String, String> result = new HashMap<>(); // BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics(); g.fillRect(0, 0, width, height); // 获取颜色 g.setColor(getRandomColor(MagicNumConstant.ONE_HUNDRED_FIVE, MagicNumConstant.ONE_HUNDRED_EIGHTY_NINE)); // 获取字体 g.setFont(getFont()); // 绘制干扰线 for (int i = 0; i < lineSize; i++) { drawLine(g); } // 绘制随机字符 String randomCode = ""; for (int i = 0; i < length; i++) { randomCode = drawString(g, randomCode, i); } g.dispose(); result.put("imgCode", randomCode); String base64Code = ""; try { //返回 base64 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", bos); byte[] bytes = bos.toByteArray(); Base64.Encoder encoder = Base64.getEncoder(); base64Code = encoder.encodeToString(bytes); } catch (Exception e) { log.debug(e.getMessage()); } result.put("data", "data:image/png;base64," + base64Code); return result; } }
后台生成图片base64,和一个唯一的key(通过这个key判断是哪张图片),后台可以通过接口传给前端图片base64和key,前端输入验证码,传给后台key和验证码去校验验证。
package com.hengtiansoft.gxrc.base.service.impl; import com.hengtiansoft.gxrc.base.service.ImgCaptchaService; import com.hengtiansoft.gxrc.base.util.ImgCaptchaUtil; import com.hengtiansoft.gxrc.common.constant.MagicNumConstant; import com.hengtiansoft.gxrc.common.entity.exception.BusinessException; import com.hengtiansoft.gxrc.common.redis.RedisOperation; import com.hengtiansoft.gxrc.common.util.UUIDUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.Map; /** * @Description: * @Author: wu * @CreateDate: 2020/11/11 17:17 */ @Service public class ImgCaptchaServiceImpl implements ImgCaptchaService { private static final String IMG_CAPTCHA = "imgCaptcha:"; @Autowired private RedisTemplate<String, Object> redisTemplate; @Autowired private ImgCaptchaUtil imgCaptchaUtil; @Override public Map<String, String> getImgCaptcha() { RedisOperation redisOperation = new RedisOperation(redisTemplate); Map<String, String> map = imgCaptchaUtil.getImgCodeBaseCode(MagicNumConstant.FOUR); String uuid = UUIDUtils.createUUID(); redisOperation.set(IMG_CAPTCHA + uuid, map.get("imgCode")); redisOperation.expire(IMG_CAPTCHA + uuid, MagicNumConstant.THIRTY_THOUSAND); map.remove("imgCode"); map.put("key", uuid); return map; } @Override public void checkImgCaptcha(String code, String key) { RedisOperation redisOperation = new RedisOperation(redisTemplate); String captcha = redisOperation.get(IMG_CAPTCHA + key); if (ObjectUtils.isEmpty(captcha) || !StringUtils.equals(captcha, code)) { throw new BusinessException("验证码错误"); } redisOperation.del(IMG_CAPTCHA + key); } }
到此,关于“Vue如何实现图片验证码生成”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。