uniapp app照片canvas新增水印
阿新 • • 發佈:2022-05-24
前言
使用uniapp實現移動APP端:拍照->壓縮拍下的圖片->獲取壓縮後的圖片資訊->使用canvas畫水印圖片->儲存本地->讀取預覽
實現
<template> <view> <view class="" v-for="(item,index) in imageList" :key="index"> <image mode="aspectFill" :src="item" @click="prevwImage(item)" class="imageStyle imageWrapper"> </image> </view> <!-- 加號 --> <view class="padding-xl"> <image src="../../static/add.jpg" mode="widthFix" class="imageStyle" @click="imageRecording"></image> </view> <!-- 水印 --> <canvas style="border: 1px solid green;position: absolute;left: -5000px;" :style="{'width':w,'height': h}" canvas-id="firstCanvas" ref="mycanvas"></canvas> </view> </template> <script> export default { data() { return { w: 0, h: 0, imgPath: "", imageList: [], nowTime: Date.now(), type: "tpurl" } }, methods: { //拍照:壓縮 imageRecording() { let that = this; uni.chooseImage({ count: 1, sizeType: ['compressed'], //選擇圖片的大小 sourceType: ['camera'], //選擇圖片的來源 success: res => { //圖片陣列 let tempFilePath = res.tempFilePaths; uni.compressImage({ src: tempFilePath[0], quality: 30, width: '40%', height: '40%', success: res2 => { that.getImageInfo(res2.tempFilePath); }, fail: () => { } }) }, fail: () => { } }) }, //獲取壓縮圖片資訊 getImageInfo(e) { let that = this; uni.getImageInfo({ src: e, success: (res) => { that.canvasWather(res) }, fail: () => { } }) }, //水印 canvasWather(res) { let that = this; let ctx = uni.createCanvasContext('firstCanvas', this); that.imgPath = res.path that.w = res.width / 2 + 'px'; that.h = res.height / 2 + 'px'; let userInfo = uni.getStorageSync('userInfo'); let realName = userInfo.realName; this.nowTime = Date.now(); setTimeout(() => { // this.ymd = this.$refs.ymdHms.dateShow; //初始化畫布 ctx.fillRect(0, 0, res.width / 2, res.height / 2); // //將圖片src放到cancas內,寬高為圖片大小 ctx.drawImage(res.path, 0, 0, res.width / 2, res.height / 2); ctx.beginPath() ctx.setFontSize(10) ctx.setFillStyle('red'); let firstY = res.height / 2 - 60; ctx.fillText('記錄人1:di', 10, res.height / 2 - 60) ctx.fillText('記錄人2:di', 10, res.height / 2 - 50) ctx.draw(false, () => { uni.canvasToTempFilePath({ //將畫布中內容轉成圖片,即水印與圖片合成 canvasId: 'firstCanvas', success: (res) => { that.saveFile(res); }, fail: (err) => { } }) }) }, 500) }, //儲存本地 saveFile(res) { let that = this; uni.saveFile({ tempFilePath: res.tempFilePath, success: (res2) => { //圖片列表獲取 that.imageList.push(res2.savedFilePath) }, fail: () => { } }) }, prevwImage(path) { let url = [path] uni.previewImage({ urls: url, success: (res) => { }, fail: () => { } }); }, } } </script> <style lang="scss" scoped> .imageWrapper { position: relative; z-index: 1; } </style>
效果