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

相关文章

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

MyBatisPlus如何优化千万级数据的CRUD

《MyBatisPlus如何优化千万级数据的CRUD》最近负责的一个项目,数据库表量级破千万,每次执行CRUD都像走钢丝,稍有不慎就引起数据库报警,本文就结合这个项目的实战经验,聊聊MyBatisPl... 目录背景一、MyBATis Plus 简介二、千万级数据的挑战三、优化 CRUD 的关键策略1. 查

Golang如何对cron进行二次封装实现指定时间执行定时任务

《Golang如何对cron进行二次封装实现指定时间执行定时任务》:本文主要介绍Golang如何对cron进行二次封装实现指定时间执行定时任务问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录背景cron库下载代码示例【1】结构体定义【2】定时任务开启【3】使用示例【4】控制台输出总结背景

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

利用Python脚本实现批量将图片转换为WebP格式

《利用Python脚本实现批量将图片转换为WebP格式》Python语言的简洁语法和库支持使其成为图像处理的理想选择,本文将介绍如何利用Python实现批量将图片转换为WebP格式的脚本,WebP作为... 目录简介1. python在图像处理中的应用2. WebP格式的原理和优势2.1 WebP格式与传统

Python中对FFmpeg封装开发库FFmpy详解

《Python中对FFmpeg封装开发库FFmpy详解》:本文主要介绍Python中对FFmpeg封装开发库FFmpy,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录一、FFmpy简介与安装1.1 FFmpy概述1.2 安装方法二、FFmpy核心类与方法2.1 FF