验证码——vue中后端返回的图片流如何显示

news/2024/10/25 11:34:23/

目录

前言

一、p调用接口获取验证码 + canvas画布渲染?

二、后端返回图片(图片流),前端显示

1.blob

2.arraybuffer

总结


前言

登录界面经常会有验证码,验证码的实现方式也有很多,我目前做过以下两种:

1.调用接口获取验证码 + canvas画布渲染

2.后端返回图片(数据流),前端显示

这两种方式都比较简单,本次项目技术栈为:vue2.6 + axsio ,接下来一起看看把~


一、p调用接口获取验证码 + canvas画布渲染?

这个比较简单,就是需要自己写一份canvas ,将后端获取过来得验证码显示出来,后续将验证码和识别码一起传递给后端,后端校验账户密码验证码是否一致。

1.编写canvas组件

这里我把他写成一个组件

<template><div class="s-canvas" id="canvas"><canvas id="s-canvas"></canvas></div>
</template><script>
export default {name: 'SIdentify',data() {return {w: '',h: '',}},props: {identifyCode: {type: String,default: '1234',},fontSizeMin: {type: Number,default: 26,},fontSizeMax: {type: Number,default: 30,},backgroundColorMin: {type: Number,default: 255,},backgroundColorMax: {type: Number,default: 255,},colorMin: {type: Number,default: 0,},colorMax: {type: Number,default: 160,},lineColorMin: {type: Number,default: 100,},lineColorMax: {type: Number,default: 255,},dotColorMin: {type: Number,default: 0,},dotColorMax: {type: Number,default: 255,},contentWidth: {type: Number,default: 121,},contentHeight: {type: Number,default: 50,},},methods: {//计算外盒子高度boxSize() {var contanier = document.getElementById('canvas')var canvas = document.getElementById('s-canvas')console.log(canvas, 'canvas')canvas.width = contanier.offsetWidthcanvas.height = contanier.offsetHeightthis.w = contanier.offsetWidththis.h = contanier.offsetHeightconsole.log(this.w, this.h, '获取到得canvas宽高')},// 生成一个随机数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 = this.randomColor(this.backgroundColorMin,this.backgroundColorMax)// console.log(this.contentWidth,this.contentHeight,"图形大小")ctx.fillRect(0, 0, this.w, this.h)// 绘制文字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(this.colorMin, this.colorMax)ctx.font =this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei'let x = (i + 1) * (this.w / (this.identifyCode.length + 1))let y = this.randomNum(this.fontSizeMax, this.h - 5)var deg = this.randomNum(-45, 45)// 修改坐标原点和旋转角度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 < 5; i++) {ctx.strokeStyle = this.randomColor(this.lineColorMin, this.lineColorMax)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 < 80; 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()},},created() {},mounted() {this.boxSize()this.drawPic()},
}
</script><style lang="stylus" scoped>
.s-canvas {width: 121pxheight: 50px;}
</style>

2.使用组件

引入该组件并命名为identifyCode

import IdentifyCode from '@/components/identifyCode'      
<Identify-code  :identifyCode="identifyCode"></Identify-code>

初始化得时候获取后端返回得验证码

created(){
this.getCode()
}
//获取验证码   
async getCode() {try {await XX().then((res) => {this.identifyCode = res})} catch (err) {console.log(err)}}

二、后端返回图片(图片流),前端显示

首先我们明确两个点:

  1. 普通请求接收的时候是json格式,图片流的接收模式可选两种:blob和arraybuffer。
  2. blob和arraybuffer本质上都是二进制数据。如果使用blob我们只需要用 window.URL.createObjectURL(res)就可以得到图片链接;如果使用arraybuffer,我们需要将其转为base64的格式。

好啦,下面就开始啦~

首先我们先设置标签变量,如下:

 <div class="getCaptcha" @click="getimgCaptcha()"><img:src="codeImg"style="width:135px;height:40px;"title="看不清,点击换一张"loading="lazy"alt="点击重新获取验证码"srcset="">
</div>

1.blob

请求设置,代码如下:

export function getCaptcha () {return request({url: /getCaptcha,method: 'get',responseType: 'blob' //选择接收方式为blob})
}

图片处理,代码如下:

  getCaptcha (e) {getCaptcha().then(res => {this.codeImg = window.URL.createObjectURL(res) // 这里调用window的URL方法console.log(this.codeImg, '地址')}).catch(err => {console.log(err)})},

2.arraybuffer

请求设置,代码如下:

// 图片验证码
export function getCaptcha () {return request({url: /getCaptch,method: 'get',responseType: 'arraybuffer'})
}

图片处理,代码如下:

  getCaptcha (e) {getCaptcha().then(res => {//1. btoa表示 base64转ASCII ,对应的还有 atob 表示 ASCII转base64//2. Unit8Arrat() 是arraybuffer里面的一种类型const url = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))this.codeImg = urlconsole.log(this.codeImg, '地址')}).catch(err => {console.log(err)})},

关于blod和arraybuffer的区别和具体用法,参考:前端二进制学习(三)

当然还有其它的二进制流,向上传文件或图片的时候用到的:File、FileReader、FormData,感兴趣可以自己去了解一下。


总结

以上就是今天要讲的内容,本文仅仅简单两种验证码的实现方式,当然还有其他的验证吗实现方式,感兴趣自己去看看把~


http://www.ppmy.cn/news/34933.html

相关文章

Android开发-Android UI与布局

01 Android UI 1.1 UI 用户界面(User Interface&#xff0c;简称 UI&#xff0c;亦称使用者界面)是系统和用户之间进行交互和信息交换的媒介&#xff0c;它实现信息的内部形式与人类可以接受形式之间的转换。软件设计可分为两个部分&#xff1a;编码设计与UI设计。 1.2 Andr…

记一次若依后台管理系统渗透

前言 最近客户开始hw前的风险排查&#xff0c;让我们帮他做个渗透测试&#xff0c;只给一个单位名称。通过前期的信息收集&#xff0c;发现了这个站点&#xff1a; 没有验证码&#xff0c;再加上这个图标&#xff0c;吸引了我注意&#xff1a; 从弱口令开始 若依默认口令为ad…

【java基础】Stream流的各种操作

文章目录基本介绍流的创建流的各种常见操作forEach方法filter方法map方法peek方法flatMap方法limit和skip方法distinct方法sorted方法收集结果收集为数组&#xff08;toArray&#xff09;收集为集合&#xff08;collect&#xff09;收集为Map关于流的一些说明&#xff08;终结操…

免费搭建个人博客

免费搭建个人博客,并发布到公网 利用hexo搭建个人博客&#xff0c;通过gitee的pages发布到公网 1 前置准备 安装git、安装node.js&#xff08;尽量选择长期支持的版本) node.js官网&#xff1a;https://nodejs.org/en/ git官网&#xff1a;https://git-scm.com/book/zh/v2 安装…

动态内存管理(上)——“C”

各位CSDN的uu们你们好呀&#xff0c;今天&#xff0c;小雅兰的内容是动态内存管理噢&#xff0c;下面&#xff0c;让我们进入动态内存管理的世界吧 为什么存在动态内存分配 动态内存函数的介绍 malloc free calloc realloc 常见的动态内存错误 为什么存在动态内存分配 我们已…

【简单理解】ubuntu中的sudo和su

参考&#xff1a; https://blog.csdn.net/liberty12345678/article/details/87686284 https://cloud.tencent.com/developer/article/1721753 简单理解ubuntu中的sudo和su一、简单理解su二、简单理解sudo su如何设置root初始密码&#xff1f;ubuntu进入root权限后如何退出&…

浅谈虚树

问题引入 你是否遇到过下面这种问题&#xff1a; SDOI2011 消耗战 在一场战争中&#xff0c;战场由 nnn 个岛屿和 n−1n-1n−1 个桥梁组成&#xff0c;保证每两个岛屿间有且仅有一条路径可达。现在&#xff0c;我军已经侦查到敌军的总部在编号为1的岛屿&#xff0c;而且他们已…

AI又进化了,声音克隆革命性突破

大家好&#xff0c;我是 Jack。 因 ChatGPT、Stable Diffusion 让 AI 在文本、图像生成领域火出了圈。 但 AI 在生成方面的能力&#xff0c;可不仅如此&#xff0c;音频领域也出现了很多优秀的项目。 我用我本人的音频数据&#xff0c;训练了一个 AI 模型&#xff0c;生成了…