Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to upload pictures and add watermarks in vue

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you vue how to upload pictures to add watermarks, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

1. Encapsulate and add watermark method

/ * add watermark * @ param {blob} file * @ param {string} el * @ returns {Promise} * / export async function addWaterMarker (file, el ='# markImg') {return new Promise (async (resolve) Reject) = > {try {/ / first compress and rotate the picture file = await compressor (file) / / convert the file blob to the picture let img = await blobToImg (file) / / create the canvas canvas let canvas = document.createElement ('canvas') canvas.width = img.naturalWidth canvas.height = img.naturalHeight let ctx = canvas.getContext (' 2d') / / Populate the uploaded image ctx.drawImage (img) 0,0, canvas.width, canvas.height) / / generate a watermark image const markEle = document.querySelector (el) const markWidth = markEle.clientWidth const scale = canvas.width * 0.25 / markWidth / / first scale the watermark and then convert it to an image markEle.style.transform = `scale (${scale}) `watermark = await htmlToCanvas (markEle) / / filled watermark ctx.drawImage (markImg) Canvas.width-markImg.width-15 * scale, canvas.height-markImg.height-15 * scale, markImg.width, markImg.height) / / convert canvas to 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') {return new Promise (async (resolve, reject) = > {try {const markImg = await html2canvas (el, {scale: 2) / / the default value window.devicePixelRatio is not used here Need to be consistent with mobile allowTaint: false, / / allow contamination of useCORS: true BackgroundColor / / 'transparent' / / background color}) resolve (markImg)} catch (error) {reject (error)})} / * compress and rotate images * @ param {blob} file * @ param {number} quality compression ratio * @ param {number} maxWidth * @ returns {Promise} * / export function compressor (file, quality = 0.6 MaxWidth) {return new Promise (resolve = > {new Compressor (file, {maxWidth, quality, success: resolve, error (err) {console.log (err.message)}

2. Use in the project

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 / / Image compression quality export default {methods: {/ / pre-upload async handleBeforeImgUpload (img, detail) {if (! img) {return} return new Promise (async (resolve, reject) = > {if (Array.isArray (img)) {if (img.length > 5) {this.$toast ('upload up to 5 copies at a time, please upload them in batches!') Reject ()} let blobs = [] for (const file of img) {/ / if the image is greater than 512k, compress if (file.size > 512x 1024 & & file.type.includes ('image/')) {file = await this.compressor (file)} / / add watermark first. Let blob = await addWaterMarker (file) blob.name = file.name blobs.push (blob)} resolve (blobs)} else {/ / images greater than 512k compress if (img.size > 512k * 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) after upload 1) this.$toast ('upload failed You can only upload photos!') / / the return in if (index = img.length-1) {$loading.hide ()} return / / forEach is equivalent to continue} if (file.size > 1024 * 1024 * 10) {this.currentItem.imgUpload.splice (detail.index + index, 1) this.$toast ('file is too large A single file cannot exceed 10MB') / / upload completed 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 ('upload failed Please try again later!) Console.error (error)} / / upload completed 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 ('upload failed You can only upload photos!') Return} if (img.file.size > = 1024 * 1024 * 10) {this.currentItem.imgUpload.splice (detail.index, 1) $loading.hide () this.$toast ('the file is too large to exceed 10MB') If return} / / is greater than 512k, compress 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 ('upload failed Please try again later!) Console.error (error)}

3. The effect is as follows

The above is all the contents of the article "how to upload pictures and add watermarks in vue". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report