preface
Recently, many technical points related to pictures have been obtained in the project, which is mainly summarized here for later reference
1. Generation and download of front-end TWO-DIMENSIONAL code (compatible with IE)
Two-dimensional code generation
An existing plug-in vuE-QR is used here
Download the plug-in
npm i vue-qr
Copy the code
Introduce the plug-in into your project
import VueQr from 'vue-qr'
Copy the code
Using the vue – qr
<el-dialog
:area="[520, 400]"
top="middle"
no-scrollbar
title="Qr code of community"
:visible.sync="qrCodeDia"
>
<el-alert
style="width: 105%; margin-left: -12px; margin-top: -12px;"
title="Please post this QR code in the community/unit, residents can scan this QR code to enter personnel information."
type="info"
simple
show-icon
:closable="false"
></el-alert>
<div v-if="qrCodeDia" id="qrcode" style="text-align: center; margin-top: 24px;">
<vue-qr :text="config.value" :size="200" :margin="0"></vue-qr>
</div>
<div slot="footer" class="dialog-footer">
<el-button @click="downloadImg()">download</el-button>
</div>
</el-dialog>
Copy the code
Corresponding generation of two-dimensional code and download methods
/ * * *@desc Expand the qr code box */
async handleShowQr(item) {
const { data } = await httpAdress.getServerInfo()
const http =
data.scheme + ': / /' + data.ip + ':' + data.port + '/ossrs/app#/AddPerson/' + item.id
this.config.value = http
this.qrCodeDia = true
},
// Determine the browser type
myBrowser() {
var userAgent = navigator.userAgent // Get the browser's userAgent string
var isOpera = userAgent.indexOf('Opera') > -1
if (isOpera) {
return 'Opera'
}
if (userAgent.indexOf('Firefox') > -1) {
return 'FF'
}
if (userAgent.indexOf('Chrome') > -1) {
return 'Chrome'
}
if (userAgent.indexOf('Safari') > -1) {
return 'Safari'
}
if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
return 'IE'
}
if (userAgent.indexOf('Trident') > -1) {
return 'Edge'}},// ② Save the picture in Internet Explorer
SaveAs5(imgURL) {
var bstr = atob(imgURL.split(', ') [1])
var n = bstr.length
var u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
var blob = new Blob([u8arr])
window.navigator.msSaveOrOpenBlob(blob, 'Community QR code. JPG')},/ * * *@author liujie22
* @desc Download qr code */
downloadImg() {
var oQrcode = document.querySelector('#qrcode img')
var url = oQrcode.src
if (this.myBrowser() === 'IE' || this.myBrowser() === 'Edge') {
// IE (browser)
this.SaveAs5(url)
} else {
/ /! Internet explorer (IE)
var a = document.createElement('a') // Create a document inserted by the a node
var event = new MouseEvent('click') // Simulate the mouse click event
a.download = 'Community QR Code' // Set the download attribute of node A
a.href = url // Assign the image SRC to the href of the a node
a.dispatchEvent(event)
}
},
Copy the code
2. H5 terminal mobile phone photo uploading and taking knowledge
Uploading and photographing methods
<template>
<div ref="imageUploadContainer" class="imageUploadContainer">
<div
v-for="(item, index) in filePreviewList"
:key="index"
class="uploadPreviewItem previewItem"
>
<img
class="prevImg"
:style="{ width: '95px', height: '133px' }"
:src="item"
@click="imgPreview(index)"
/>
<i class="van-icon van-icon-clear deleteImgIcon" @click="deleteImg(index)"></i>
</div>
<div
v-if="max === -1 || fileList.length < max"
ref="uploadBtn"
class="uploadBtn previewItem"
@click="onAddFileBtnClick"
>
<i class="van-icon van-icon-plus uploadeIcon"></i>
<input type="file" accept="image/jpg" @change="fileChange" />
</div>
</div>
</template>
Copy the code
Image upload and compression methods
// File selection change event
// Uploading files without suffixes will failTODO:
async fileChange(e) {
// Check the quantity
if (this.max && this.fileList.length >= 6) {
Toast('Quantity limit exceeded')
return false
}
let file = e.target.files[0]
// The file object does not exist if you deselect it
if(! file) {return false
}
const that = this
// Check the image size
const ms = file.size / 1024
if (this.size && ms > this.size) {
that.photoCompress(
file,
{
width: 400.height: 600.// Call the compressed image method
quality: 0.9
},
async function(base64Codes) {
let bl = that.base64UrlToBlob(base64Codes)
// Check the image size
const mss = bl.size / 1024
if (that.size && mss > that.size) {
Toast(` over${that.size}KB size limit ')}else if (mss < 10) {
Toast('Cannot be smaller than the 10KB size limit')}else {
if (that.base64) {
bl = await that.toDataURL(bl)
}
that.trigger(bl)
}
}
)
} else if (ms < 10) {
Toast('Cannot be smaller than the 10KB size limit')}else {
if (this.base64) {
file = await this.toDataURL(file)
}
this.trigger(file)
}
},
Copy the code
/* * compressed image *file: file (type is image format), *obj: compressed object width, height, quality(0-1) *callback: container or callback function */
photoCompress(file, obj, callback) {
const that = this
const ready = new FileReader() /* Starts reading the contents of the specified File object. When the read operation is complete, a urL-formatted string is returned. */
ready.readAsDataURL(file)
ready.onload = function() {
const re = this.result
that.canvasDataURL(re, obj, callback) // Start compression}},Copy the code
/* Compress canvas data images */
/* Base64 */
canvasDataURL(path, obj, callback) {
const img = new Image()
img.src = path
img.onload = function() {
const that = this // refers to img // defaults to proportional compression
let w = that.width
let h = that.height
const scale = w / h
w = obj.width || w
h = obj.height || w / scale
const quality = obj.quality // The default image quality is 0.7 // Generate canvas
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d') // Create the properties node
const anw = document.createAttribute('width')
anw.nodeValue = w
const anh = document.createAttribute('height')
anh.nodeValue = h
canvas.setAttributeNode(anw)
canvas.setAttributeNode(anh)
ctx.drawImage(that, 0.0, w, h) // Image quality
// The smaller the quality value, the more blurred the image is drawn
const base64 = canvas.toDataURL('image/jpeg', quality) // The callback function returns the base64 value
callback(base64)
}
},
Copy the code
/** * base64 to Blob format and file format */
base64UrlToBlob(urlData) {
const arr = urlData.split(', ')
const mime = arr[0].match(/ : (. *?) ; /) [1] // Remove the url header and convert it to byte
const bstr = atob(arr[1]) // Handle exceptions to convert ASCII codes less than 0 to greater than 0
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
} // return new blob ([u8arr], {type: mime})
const filename = Date.parse(new Date()) + '.jpg' // 转file
return new File([u8arr], filename, { type: mime })
},
Copy the code
/ * * *@Desc: Transfers binary data to Base65 */
toDataURL(blob) {
return new Promise((resolve, reject) = > {
const a = new FileReader()
a.onload = e= > {
resolve(e.target.result)
}
a.readAsDataURL(blob)
})
},
Copy the code
/ * * *@Desc: triggers an event that calls the parent component method */
trigger(tar) {
this.fileList.concat([tar])
if (typeof tar === 'string') {
this.$emit('afterRead', { base: tar })
} else {
this.$emit('afterRead', { base: tar })
}
},
Copy the code
Pictures show
Computed: {// Preview list filePreviewList() {return this.filelist. map(item => {return typeof item === 'object'? window.URL.createObjectURL(item) : item }) } },Copy the code