上传图片时添加水印的组件

 水印内容为: 时间  基地库

仅支持app,加水印在其他平台加不上,只能显示原图片

// dUpload
<template>
	<view>
		<view>
			<u-form ref="uForm">
				<!-- // 是否允许删除
				// 是否展示进度 
				//图片来源 
				// 上传前钩子 
				// 上传携带的头信息,对象形式 
				// 上传额外携带的参数 -->
				<u-form-item label="照片信息:" prop="photo" label-width="160">
					<u-upload 
						width="160" 
						:source-type="sourceType"
						:before-upload="beforeUpload" 
						:action="action" 
						:header='upHeader' 
						:form-data="formData"
						:max-count="count" 
						:show-progress="true"
						:size-type="sizeType" 
						@on-remove="deleteItem" 
						@on-success='onSuccess'
						:file-list="details.fileLists">
					</u-upload>
				</u-form-item>
			</u-form>
			<view style="position: absolute;top: -999999px;">
				<view>
					<canvas style="width: 1000px;height: 1000px;" canvas-id="firstCanvas"></canvas>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		baseUrl
	} from '../../config/config.js';        // 接口中的前缀,根据实际情况来
	export default {
		name:"dUpload",
		props:{
			libraryName:{
				type: String,
				default: '',
			},
			detail: {   
				type: Object,
			},
			MaxCount: {
				type: Number,
				default: 3
			}
		},
		data() {
			return {
				action: 'mongo/save',
				upHeader: {},
				sizeType: ['compressed'],		// 压缩画质
				header: {
					'X-Access-Token': uni.getStorageSync('token')
				},
				formData: {
					'biz': 'mobile'
				},
				sourceType: ['camera'],
				imageLists: [],
				text: '',		// 时间
				details:{},
				count: 3,
				libraryNames: ''
			};
		},
		created() {
			this.action = baseUrl + 'mongo/save'        // 上传图片的接口
			const token = uni.getStorageSync("userToken")        // 接口需要的token
			this.upHeader = {
				'X-Access-Token': token 
			}
			setTimeout(()=>{
				this.libraryNames = this.libraryName
				this.details = this.detail
				this.count = this.MaxCount
			},200)
			this.details.fileLists = []
			this.details.ids = []
			
		},
		methods:{
			// 上传照片
			async beforeUpload(index, list) {
				uni.showLoading({
					title: '上传中...',
				})
				var data = await this.getWatermark(index, list);
				uni.hideLoading()
				return data;
			},
			//照片添加水印
			getWatermark(index, list) {
				return new Promise((resolve, reject) => {
					var that = this;
					uni.getImageInfo({
						src: list[index].url,
						success: (ress) => {
							var myDate = new Date();
							this.text = myDate.getFullYear() + '-' + (myDate.getMonth() + 1) + '-' +
								myDate.getDate() + ' ' + myDate.getHours() + ':' + myDate
							.getMinutes() + ':' + myDate.getSeconds()
							let ctx = uni.createCanvasContext('firstCanvas'); //创建画布
							//将图片src放到cancas内,宽高为图片大小
							ctx.drawImage(list[index].url, 0, 0, ress.width / 3, ress.height / 3)
							ctx.setFontSize(30) //字体大小
							ctx.setFillStyle('#ffffff') //字体颜色
							let textToWidth = ress.width / 14 * 0.3; //字体宽度
							let textToHeight = ress.height / 3 * 0.9; //字体高度
							let textToWidths = ress.width / 14 * 0.3; //字体宽度
							let textToHeights = ress.height / 2.8 * 0.9; //字体高度
							ctx.fillText(this.text, textToWidth, textToHeight) // 设置字体
							ctx.fillText(this.libraryNames, textToWidths, textToHeights) // 设置字体
							ctx.draw(false, () => {
								setTimeout(() => { //使用定时是因为制作水印需要时间,设置定时才不会出bug
									uni.canvasToTempFilePath({ //将画布中内容转成图片,即水印与图片合成
										width: ress.width / 3, // 画布宽
										height: ress.height / 3, // 画布高
										canvasId: 'firstCanvas',
										success: (res) => {
											list[index].url = res.tempFilePath
											uni.saveImageToPhotosAlbum({ //保存到手机
												filePath: res.tempFilePath,
												success: (re) => {
													resolve(true);
												}
											})
										}
									})
								}, 500)
							});
						}
					})
				})
			},
			// 清除图片的ids
			deleteItem(index, lists, name) {
				// this.imgIds = ''
				console.log(lists)
				this.detail.ids = []
				lists.map((item) => {
					this.detail.ids.push(item.response.id)
				})
				setTimeout(()=>{
					this.$emit('deleteImageData',this.detail.ids)		//  父组件的deleteImageData方法中需要先清空this.detail.id
				},200)
			},
			// 上传成功之后
			onSuccess(data, index, lists, name) {
				// this.detail.ids.push(data.id)
				// console.log(this.detail,data.id)
				console.log(this.libraryName)
				console.log(this.libraryNames)
				this.$emit('getImageData',data.id)		// 父组件中getImageData方法需要给this.detail.ids一个赋值
				uni.showToast({
					title: '上传成功',
					duration: 2000,
					icon: 'none'
				})
			},
			// JS字符串截取(获取指定字符后面的所有字符内容)
			getSub(obj) {
				let index = obj.lastIndexOf('\/')
				obj = obj.substring(index + 1, obj.length)
				return obj
			},
		}
	}
</script>

<style lang="less">

</style>
  • detail:Array         包含图片列表fileLists 的数组 
  • libraryName: String  水印中的基地库

 调用的时候

<dUpload ref="dUpload" :libraryName="inData.libraryName" :MaxCount="MaxCount" :detail="inData" @getImageData="getImageData" @deleteImageData='deleteImageData'></dUpload>


import dUpload from '../../../components/dUpload/dUpload.vue'


components: {
	dUpload
},

 写的还有很多不足,仅满足项目使用

猜你喜欢

转载自blog.csdn.net/weixin_45849072/article/details/119998082
今日推荐