vue實(shí)現(xiàn)上傳圖片添加水印
本文實(shí)例為大家分享了vue上傳圖片添加水印的具體實(shí)現(xiàn)代碼,供大家參考,具體內(nèi)容如下
1、封裝添加水印方法
/**
* 添加水印
* @param {blob} file
* @param {string} el
* @returns {Promise}
*/
export async function addWaterMarker(file, el = '#markImg') {
return new Promise(async (resolve, reject) => {
try {
// 先壓縮和旋轉(zhuǎn)圖片
file = await compressor(file)
// 將文件blob轉(zhuǎn)換成圖片
let img = await blobToImg(file)
// 創(chuàng)建canvas畫(huà)布
let canvas = document.createElement('canvas')
canvas.width = img.naturalWidth
canvas.height = img.naturalHeight
let ctx = canvas.getContext('2d')
// 填充上傳的圖片
ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
// 生成水印圖片
const markEle = document.querySelector(el)
const markWidth = markEle.clientWidth
const scale = canvas.width * 0.25 / markWidth
// 先縮放水印再轉(zhuǎn)成圖片
markEle.style.transform = `scale(${scale})`
const markImg = await htmlToCanvas(markEle)
// 填充水印
ctx.drawImage(markImg, canvas.width - markImg.width - 15 * scale, canvas.height - markImg.height - 15 * scale, markImg.width, markImg.height)
// 將canvas轉(zhuǎn)換成blob
canvas.toBlob(blob => resolve(blob))
} catch (error) {
reject(error)
}
})
}
function blobToImg(blob) {
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.addEventListener('load', () => {
let img = new Image()
img.src = reader.result
img.addEventListener('load', () => resolve(img))
})
reader.readAsDataURL(blob)
})
}
export function htmlToCanvas(el, backgroundColor = 'rgba(0,0,0,.1)') {
return new Promise(async (resolve, reject) => {
try {
const markImg = await html2canvas(el, {
scale: 2, //此處不使用默認(rèn)值window.devicePixelRatio,需跟移動(dòng)端保持一致
allowTaint: false, //允許污染
useCORS: true,
backgroundColor //'transparent' //背景色
})
resolve(markImg)
} catch (error) {
reject(error)
}
})
}
/**
* 壓縮和旋轉(zhuǎn)圖片
* @param {blob} file
* @param {number} quality 壓縮比例
* @param {number} maxWidth
* @returns {Promise}
*/
export function compressor(file, quality = 0.6, maxWidth = 750) {
return new Promise(resolve => {
new Compressor(file, {
maxWidth,
quality,
success: resolve,
error(err) {
console.log(err.message)
}
})
})
}
2、項(xiàng)目中使用
<!-- 圖片上傳 -->
<div class="flex mt20" v-if="item.questionType === 4">
<van-uploader
v-model="item.imgUpload"
multiple="true"
lazy-load
:deletable="!isDisabled"
:disabled="isDisabled"
@delete="handleDeleteImg({ ...arguments, item })"
:before-read="handleBeforeImgUpload"
:after-read="handleAfterImgUpload"
@click.native="currentItem = item"
/>
</div>
<script>
import {
getTaskDetail,
userExecute,
submitFlow,
rejectFlow,
} from '@/api/myTask';
import { uploadOSS } from '@/utils/oss';
import { parseTime, addWaterMarker } from '@/utils';
import { ImagePreview } from 'vant';
import Compressor from 'compressorjs';
const fileExtensions = ['xlsx', 'xls', 'docx', 'doc', 'pdf'];
const quality = 0.2; //圖片壓縮質(zhì)量
export default {
methods: {
// 上傳前
async handleBeforeImgUpload(img, detail) {
if (!img) {
return
}
return new Promise(async (resolve, reject) => {
if (Array.isArray(img)) {
if (img.length > 5) {
this.$toast('一次最多上傳5張,請(qǐng)分批次上傳!')
reject()
}
let blobs = []
for (const file of img) {
// 大于512k的圖片則先壓縮
if (file.size > 512 * 1024 && file.type.includes('image/')) {
file = await this.compressor(file)
}
// 添加水印
let blob = await addWaterMarker(file)
blob.name = file.name
blobs.push(blob)
}
resolve(blobs)
} else {
// 大于512k的圖片則先壓縮
if (img.size > 512 * 1024 && img.type.includes('image/')) {
img = await this.compressor(img)
}
const blob = await addWaterMarker(img)
blob.name = img.name
resolve(blob)
}
})
},
// 上傳后
async handleAfterImgUpload(img, detail) {
try {
$loading.show()
if (Array.isArray(img)) {
img.forEach(async ({ file }, index) => {
if (!file.name || !file.type.includes('image/')) {
this.currentItem.imgUpload.splice(detail.index + index, 1)
this.$toast('上傳失敗,只能上傳照片!')
// 上傳完成
if (index === img.length - 1) {
$loading.hide()
}
return //forEach里的return相當(dāng)于continue
}
if (file.size > 1024 * 1024 * 10) {
this.currentItem.imgUpload.splice(detail.index + index, 1)
this.$toast('文件太大,單個(gè)文件不能超過(guò)10M!')
// 上傳完成
if (index === img.length - 1) {
$loading.hide()
}
return
}
try {
const { fileName, url } = await uploadOSS(file)
this.currentItem.answer.push({
url,
})
} catch (error) {
this.currentItem.imgUpload.splice(detail.index + index, 1)
this.$toast('上傳失敗,請(qǐng)稍后重試!')
console.error(error)
}
// 上傳完成
if (index === img.length - 1) {
$loading.hide()
}
})
} else {
if (!img.file.type.includes('image')) {
this.currentItem.imgUpload.splice(detail.index, 1)
$loading.hide()
this.$toast('上傳失敗,只能上傳照片!')
return
}
if (img.file.size >= 1024 * 1024 * 10) {
this.currentItem.imgUpload.splice(detail.index, 1)
$loading.hide()
this.$toast('文件太大,不能超過(guò)10M!')
return
}
// 大于512k則先壓縮
let file = img.file
const { fileName, url } = await uploadOSS(file)
this.currentItem.answer.push({
url,
})
$loading.hide()
}
} catch (error) {
this.currentItem.imgUpload.splice(detail.index, 1)
$loading.hide()
this.$toast('上傳失敗,請(qǐng)稍后重試!')
console.error(error)
}
}
}
感謝龍哥的指導(dǎo);
3、效果如下

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Vue中數(shù)組和對(duì)象更改后視圖不刷新的問(wèn)題
這篇文章主要介紹了Vue中數(shù)組和對(duì)象更改后視圖不刷新的問(wèn)題,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
Vue3手動(dòng)清理keep-alive組件緩存的方法詳解
這篇文章主要為大家詳細(xì)介紹了Vue3中手動(dòng)清理keep-alive組件緩存的方法,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04
解決vue打包后vendor.js文件過(guò)大問(wèn)題
這篇文章主要介紹了解決vue打包后vendor.js文件過(guò)大問(wèn)題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-07
使用Vue3優(yōu)雅地實(shí)現(xiàn)表格拖動(dòng)排序
在?Vue.js?中主要通過(guò)第三方庫(kù)實(shí)現(xiàn)表格拖動(dòng)排序功能,其中最常用的庫(kù)是?SortableJS,下面我們就來(lái)看看如何使用SortableJS實(shí)現(xiàn)表格拖動(dòng)排序吧2025-01-01
vue?router如何實(shí)現(xiàn)tab切換
這篇文章主要介紹了vue?router如何實(shí)現(xiàn)tab切換,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04
vue中for循環(huán)更改數(shù)據(jù)的實(shí)例代碼(數(shù)據(jù)變化但頁(yè)面數(shù)據(jù)未變)
這篇文章主要介紹了vue中for循環(huán)更改數(shù)據(jù)的實(shí)例代碼(數(shù)據(jù)變化但頁(yè)面數(shù)據(jù)未變)的相關(guān)資料,需要的朋友可以參考下2017-09-09
el-radio-group中的area-hidden報(bào)錯(cuò)的問(wèn)題解決
本文主要介紹了el-radio-group中的area-hidden報(bào)錯(cuò)的問(wèn)題解決,下面就來(lái)介紹幾種解決方法,具有一定的參考價(jià)值,感興趣的可以了解一下2025-04-04
vue2+electron項(xiàng)目搭建過(guò)程
文章介紹了如何使用Vue CLI 2搭建Vue項(xiàng)目,并添加Electron插件vue-cli-plugin-electron-builder來(lái)創(chuàng)建一個(gè)Vue+Electron項(xiàng)目,文章還提供了啟動(dòng)和打包項(xiàng)目的方法,并提示了下載國(guó)內(nèi)網(wǎng)較慢的文件時(shí)可以先注釋掉代碼進(jìn)行調(diào)試,感興趣的朋友一起看看吧2025-01-01

