uniapp 图片添加水印代码封装(优化版、图片上传压缩、生成文字根据页面自适应比例、增加文字背景色

本文主要是介绍uniapp 图片添加水印代码封装(优化版、图片上传压缩、生成文字根据页面自适应比例、增加文字背景色,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

uniapp 图片添加水印代码封装(优化版、图片上传压缩、生成文字根据页面自适应比例、增加文字背景色

多张照片上传封装

<template><view class="image-picker"><uni-file-picker v-model="imageValue" :auto-upload="false" :title="title" :limit="limit":image-styles="imageStyles" :file-mediatype="fileMediatype" :mode="mode" @select="select"><view v-if="loading" class="form-item-column-center"><u-loading-icon text="上传中" textSize="12" :vertical="true"></u-loading-icon></view><view v-else class="form-item-column-center"><u-icon name="camera" size="28"></u-icon><view :style="{ marginTop: '5px'}">上传照片</view></view></uni-file-picker><view class="watermark-canvas"><canvas id="watermark-canvas" :style="{ width: canvasWidth, height: canvasHeight }"canvas-id="watermark-canvas" v-if="flag" /></view></view>
</template><script>import {imageUpload,} from '@/api/system/applet.js' //图片上传import {imageChoose, //拿到后台图片上传链接} from '@/utils/public.js'export default {name: 'ImageWatermarkPicker',props: {limit: {type: [Number, String],default: 1,},title: {type: String,default: null,},mode: {type: String,default: 'grid',},fileMediatype: {type: String,default: 'image',},imageStyles: {type: Object,default: null,},watermark: {type: Boolean,default: true,},// #ifdef VUE3modelValue: {type: Array,default () {return []},},// #endif// #ifndef VUE3value: {type: Array,default () {return []},},// #endif},emits: ['input', 'update:modelValue'],data() {return {flag: false, //绘制显示imageValue: [],canvasWidth: '1080px',canvasHeight: '2160px',longitude: '', //坐标latitude: '', //y坐标addressName: '', //传入公司地址loading: false,oldImageslength: null, //上传时照片个数}},watch: {imageValue(newVal) {// #ifdef VUE3this.$emit('update:modelValue', newVal)// #endif// #ifndef VUE3this.$emit('input', newVal)// #endifthis.$emit('change', newVal)},// #ifndef VUE3value: {handler(newVal) {this.imageValue = newVal},immediate: true,},// #endif// #ifdef VUE3modelValue: {handler(newVal) {this.imageValue = newVal},immediate: true,},// #endif},methods: {// 检测图片,确保图片存在checkImage(url) {const checkNum = 5let currentCheckNum = 1return new Promise((resolve, reject) => {process()function process() {uni.getImageInfo({src: url,success: function(image) {resolve(image)},fail: function(err) {if (checkNum <= currentCheckNum) {uni.showToast({title: '图片上传失败',icon: 'none'})reject(err)} else {currentCheckNum++const timer = setTimeout(() => {clearTimeout(timer)process()}, 300)}},})}})},async select(e) {this.oldImageslength = e.tempFiles.lengthfor (let tempFile of e.tempFiles) {await this.watermarkProcess(tempFile)}},async watermarkProcess(tempFile) {const {name,size,extname,uuid,path} = tempFilelet url = nulllet photo = null// 添加水印if (this.watermark) {url = await this.addWatermark(path)}// 上传图片url = await this.uploadFile(url)// 检测图片,确保图片存在await this.checkImage(url)this.imageValue = [...this.imageValue,{name,extname,url,photo,size,uuid,},]},getHeightOffset(height, index, fontSize) {return index == 0 ? (height - fontSize) : (height - (index * fontSize) - fontSize) - (index * (fontSize /3))},// 异步添加水印async addWatermark(tempFilePath) {// #ifdef MP-WEIXINthis.addressName = '测试位置'this.latitude = 119.651this.longitude = 80.654// #endifthis.flag = trueif (this.loading == true) {uni.showLoading({title: "上传图片",mask: true,})}return new Promise((resolve, reject) => {uni.getImageInfo({src: tempFilePath,success: async (res) => {// 设置画布高度和宽度this.canvasWidth = `${res.width}px`this.canvasHeight = `${res.height}px`await this.sleep(200) // 某些平台 canvas 渲染慢,需要等待const ctx = uni.createCanvasContext('watermark-canvas', this)ctx.clearRect(0, 0, res.width, res.height)ctx.beginPath()ctx.drawImage(tempFilePath, 0, 0)// 第一个参数是图片 第二、三是图片在画布位置 第四、五是将图片绘制成多大宽高(不写四五就是原图宽高)let size// 根据图片纵横比设置字体大小,背景色相比一般ctx.fillStyle = 'rgba(0,0,0,0.1)'; // 设置背景色if (res.width / res.height > 1) {size = Math.floor(res.height / 26)//这个背景不一定适用,自行调整ctx.fillRect(0, res.height - (size*6), res.width, size*6); // 填充整个 Canvas 区域	} else {size = Math.floor(res.width / 26)ctx.fillRect(0, res.height - (size*7), res.width, size*7); // 填充整个 Canvas 区域	}let fontSize = sizectx.setFontSize(fontSize)ctx.shadowColor = "rgba(0,0,0,1.0)";//设置字体阴影,真机未生效ctx.shadowOffsetX = 5ctx.shadowOffsetY = 5let max = (res.width - fontSize) / fontSize //图片上一行能显示的最大字数let marks = []let address = "地址:" + this.addressNamelet location = "坐标:" + this.latitude + ',' + this.longitudelet fillTexts = [address, location, time]fillTexts.forEach((mark, index) => {//测量出最长文字的宽// console.log('文字宽:'+ctx.measureText(mark).width)if (mark.length <= max) {marks.push({mark: mark, //水印文字start: fontSize / 2 //第一个字的起点位置})} else {marks.push({mark: mark.substring(max),start: fontSize / 2 + fontSize *3 //第一个字的起点位置,+fontSize*3是因为此水印为当前mark的换行,因此缩进3字符})marks.push({mark: mark.substring(0, max),start: fontSize / 2 //第一个字的起点位置})}})// 绘制水印背景另外写法,实测不太好用// ctx.fillStyle = 'rgba(0,0,0,0.1)'; // 设置背景色// ctx.fillRect(0, this.getHeightOffset(res.height, 4, fontSize), res.width,this.getHeightOffset(res.height, 4, fontSize)); // 填充整个 Canvas 区域	//绘制水印文字marks.forEach((mark, index) => {ctx.setFillStyle("rgba(250, 250, 250,1.0)")ctx.fillText(mark.mark, mark.start, this.getHeightOffset(res.height, index, fontSize))});ctx.draw(false, async () => {await this.sleep(500) // 某些平台 canvas 渲染慢,需要等待uni.canvasToTempFilePath({canvasId: 'watermark-canvas',destWidth: res.width,destHeight: res.height,fileType: 'jpg',quality: 0.8,success: (fileRes) => {this.flag = falseresolve(fileRes.tempFilePath)},fail: (err) => {console.log('[Error draw]', err)uni.showToast({title: err.errMsg,icon: 'none'})reject()},},this,)})},fail: (err) => {console.log('[Error getImageInfo]', err)uni.showToast({title: err.errMsg,icon: 'none'})reject()},})})},//此位置为我上传后台的写法,具体可按照自己的填写async uploadFile(path) {let image = imageChoose(path)const res = await imageUpload(image).then(response => {this.oldImageslength--this.loading = this.oldImageslength == 0 ? false : truethis.oldImageslength == 0 ? uni.hideLoading() : ''return response.data.url})return res},sleep(millisecond) {return new Promise((resolve) => {setTimeout(resolve, millisecond)})},},}
</script><style lang="scss" scoped>canvas {position: absolute;left: 2000upx;}.image-picker {position: relative;.form-item-column-center {display: flex;align-items: center;justify-content: center;flex: 1;flex-direction: column;}.watermark-canvas {position: absolute;top: 5px;left: 5px;width: 1px;height: 1px;overflow: hidden;}}
</style>

应用实例

照片上传实例
<template><view><photoList   v-model="baseFormData.faceImgsFirst"  :limit="1"/></view>
</template>
<script>
import photoOne from '@/pages/public/photoOne/photoOne.vue'
export default{components: {photoOne},data(){return{baseFormData:{}}},methods:{}
}
</script>

动态表单照片添加水印(直接使用)

注意imagelists必填,避免出现删除不一致现象,发送为父级数据


<template><view><uni-forms><uni-forms-item label="照片" required :rules="[{required: true,errorMessage: '最少一张照片'}]":name="['inspectionCustodyWorkLogDetailBoList',index,'imagelist']" label-width="100rpx"><view class="form-item"><photoList   v-model="baseFormData.faceImgsFirst"  :limit="1"/></view></uni-forms-item></uni-forms></view>
</template>
<script>
import photoOne from '@/pages/public/photoOne/photoOne.vue'
export default{components: {photoOne},data(){// 基础表单数据baseFormData: {inspectionCustodyWorkLogDetailBoList: [], },},methods:{}
}
</script>

这篇关于uniapp 图片添加水印代码封装(优化版、图片上传压缩、生成文字根据页面自适应比例、增加文字背景色的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/983546

相关文章

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取

Java中Map.Entry()含义及方法使用代码

《Java中Map.Entry()含义及方法使用代码》:本文主要介绍Java中Map.Entry()含义及方法使用的相关资料,Map.Entry是Java中Map的静态内部接口,用于表示键值对,其... 目录前言 Map.Entry作用核心方法常见使用场景1. 遍历 Map 的所有键值对2. 直接修改 Ma

Python基于微信OCR引擎实现高效图片文字识别

《Python基于微信OCR引擎实现高效图片文字识别》这篇文章主要为大家详细介绍了一款基于微信OCR引擎的图片文字识别桌面应用开发全过程,可以实现从图片拖拽识别到文字提取,感兴趣的小伙伴可以跟随小编一... 目录一、项目概述1.1 开发背景1.2 技术选型1.3 核心优势二、功能详解2.1 核心功能模块2.

Go语言如何判断两张图片的相似度

《Go语言如何判断两张图片的相似度》这篇文章主要为大家详细介绍了Go语言如何中实现判断两张图片的相似度的两种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 在介绍技术细节前,我们先来看看图片对比在哪些场景下可以用得到:图片去重:自动删除重复图片,为存储空间"瘦身"。想象你是一个

使用Python实现base64字符串与图片互转的详细步骤

《使用Python实现base64字符串与图片互转的详细步骤》要将一个Base64编码的字符串转换为图片文件并保存下来,可以使用Python的base64模块来实现,这一过程包括解码Base64字符串... 目录1. 图片编码为 Base64 字符串2. Base64 字符串解码为图片文件3. 示例使用注意

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

pandas实现数据concat拼接的示例代码

《pandas实现数据concat拼接的示例代码》pandas.concat用于合并DataFrame或Series,本文主要介绍了pandas实现数据concat拼接的示例代码,具有一定的参考价值,... 目录语法示例:使用pandas.concat合并数据默认的concat:参数axis=0,join=