uniapp 拍照上传 并压缩图片添加水印

1.预览图片

let data = {
   problemPhoto: 'http://test.png' 
}
previewImage(data) {
				    if(!data.problemPhoto){
					uni.showToast({
						icon:"none",
						title:"暂无照片"
					})
					return
				}
				console.log(data.problemPhoto.split(";"))
				uni.previewImage({
					current:0,
					urls: data.problemPhoto?data.problemPhoto.split(";"):[],
				});
			},

2.拍照上传图片方式一

        使用uniapp 自带的api拍照

<template>
	<view class="wra">
		<!-- <com-button-page :data='data'>
		</com-button-page> -->
		<view class="upload-img">
			<image src="../../../static/images/QR_code.png" @tap="onGetImgClick"></image>
		</view>
		<view class="imgList">
			<view class="imgbox" v-for="(item,index) in imageList" :key='index'>
				<image :src="item" mode="aspectFit" @click="previewImage(imageList)"></image>
			</view>
			<view title="删除第一张" class="del" v-show="imageList.length>0" @click="onDeleteClick(0)">
			</view>
		</view>
	</view>
</template>

<script>
	import URL from "../../../static/js/interface.js"
	import util from "../../../static/js/utils.js"
	import params from "../../../static/js/params.js"
	// import comButtonPage from '@/components/comButtonPage'
	export default {
		data() {
			return {
				imageList: [],
			}
		},
		methods: {
			onGetImgClick() {
				const that = this
				uni.chooseImage({
					count: 6, // 最多可以选择的图片张数,默认9
					sizeType: ['original', 'compressed'], //original 原图,compressed 压缩图,默认二者都有
					sourceType: ['album', 'camera'], //album 从相册选图,camera 使用相机,默认二者都有。如需直接开相机或直接选相册,请只使用一个选项
					success: function(res) {
						const len = that.imageList.length
						if (len >= 6) {
							uni.showToast({
								title: '图片最多上传6张'
							})
						} else {
							for (let i = 0; i < 6 - len; i++) {
								if (res.tempFilePaths[i]) {
									that.imageList.push(res.tempFilePaths[i])
									console.log(that.imageList)
								}

							}
						}
					},
					// .bind(that)
				})
			},
			// 删除图片
			onDeleteClick(index) {
				this.imageList.splice(index, 1)
			},
			previewImage(data) {
				// 预览多张图片
				if(!data){
					uni.showToast({
						icon:"none",
						title:"暂无照片"
					})
					return
				}
				uni.previewImage({
					current:0,
					urls: data
				});
			},
		}
	}
</script>

<style scoped>
	.upload-img {
		height: 200upx;
		width: 200upx;
	}
	.upload-img image {
		width: 100%;
		height: 100%;
	}
	.imgList {
		display: flex;
	}
	.imgbox, .del {
		width: 200upx;
		height: 200upx;
	}
	.imgbox image {
		width: 100%;
		height: 100%;
	}
	.del {
		background: url(../../../static/images/checkTypeMap/tzc_t.png) no-repeat center;
	}
</style>

效果图:

2.拍照上传图片方式二

        使用uniapp + HTML5 API 中的camera对象拍照

onGetImgClick() {
	var camera=plus.camera.getCamera() // 获取camera对象
	var resolution=camera.supportedImageResolutions // 获取字符串数组,摄像头支持的摄像分辨率
	camera.captureImage((res)=>{
		console.log(res)
		this.imageList.push(res)
		}, (error)=>{
			console.log(error)
		}, {resolution:resolution[resolution.length-1],format:"jpg"})
		},

 效果图:

3.压缩图片并添加水印

<view class="takingPictures" @click="takingPictures()">
					<image style="width: 46upx;height: 38upx;" src="/static/images/icon_takePicture.png" mode="">
					</image>
				</view>
<water-mark v-if="imgUrl" @getPhotoUrl="getPhotoUrl" :imgUrl="imgUrl"></water-mark>

takingPictures() {
				var camera = plus.camera.getCamera()
				var resolution = camera.supportedImageResolutions
				// console.log(resolution)
				camera.captureImage((res) => {
					console.log('照片', res);
					this.imgUrl = res
				}, (res) => {}, {
					resolution: resolution[resolution.length - 1],
					format: "jpg"
				})
				/* uni.chooseImage({
					count: 1, //可以选择图片的张数
					sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有
					sourceType: ['camera'], //从相册选择  默认是两个都有
					success: (res) => {
						console.log(res);
						// this.pictures.push(res.tempFilePaths[0]) 
						this.imgUrl = res.tempFilePaths[0]
					}
				}); */
			},


getPhotoUrl(url) {
				this.imgUrl = ""
				this.pictures.push(url)
				util.uploadFile(URL.UPLOAD_UPLOAD, url, (results) => {
					console.log(results)
					// results=JSON.parse(results)
					// console.log(results.data)
					// this.pictures.push(results.data)
				})
			},

<template name="createWaterMark">
	<view class="createWaterMark">
		<view class="createWaterMark_content" :style="{'height':(imgInfo.height*2)+'px'}">
			<canvas canvas-id="waterMark"></canvas>
		</view>
		<helang-compress ref="helangCompress"></helang-compress>
	</view>

</template>

<script>
	import helangCompress from '../../components/helang-compress/helang-compress.vue';
	export default {
		data() {
			return {
				imgInfo: {},
				screenW: "",
				ctx: null
			}
		},
		components: {
			helangCompress
		},
		props: ['imgUrl', 'msg'],
		created() {
			// console.log(this.imgUrl)
			uni.showLoading({})
			this.screenW = uni.getSystemInfoSync().screenWidth


			this.getImgInfo(this.imgUrl)
		},
		onShow() {
			// console.log(this.imgUrl)
		},
		methods: {

			getImgInfo(url) {
				uni.getImageInfo({
					src: url,
					success: (results) => {
						1.压缩照片为base64格式
						this.$refs.helangCompress.compress({ 
							src: url,
							maxSize: 800,
							fileType: 'jpg',
							quality: 0.85,
							minSize: 340 //最小压缩尺寸,图片尺寸小于该时值不压缩,非H5平台有效。若需要忽略该设置,可设置为一个极小的值,比如负数。
						}).then((base64) => {
							// 压缩成功回调
							console.log('压缩pass', base64);
							this.imgInfo = {
								// path:results.path,
								path: base64,
								width: this.screenW * 2,
								height: results.height * this.screenW * 2 / results
									.width
							}
							setTimeout(this.drawMark, 500)
						}).catch((err) => {
							console.log('压缩fail');
							// 压缩失败回调
						})

					}
				});
			},
            // canvas 添加水印
			drawMark() {
				var data = this.imgInfo

				var ctx = uni.createCanvasContext("waterMark", this)
				ctx.drawImage(data.path, 0, 0, data.width, data.height)

				ctx.setFillStyle("#ff0000")
				ctx.setFontSize(40)
                // 添加水印文本
				ctx.fillText(this.getDate(), 30, data.height - 30)
				if (this.msg) {
					ctx.fillText(this.msg, 30, data.height - 70)
				}
				ctx.draw()
				setTimeout(this.getImg, 3500)
			},
			getImg() {
                // canvas转成图片
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: this.imgInfo.width,
					height: this.imgInfo.height,
					destWidth: this.imgInfo.width,
					destHeight: this.imgInfo.height,
					canvasId: 'waterMark',
					fileType: "jpg",
					quality: 0.65,
					success: (res) => {
						// 在H5平台下,tempFilePath 为 base64
						// console.log(res.tempFilePath)
						this.$emit("getPhotoUrl", res.tempFilePath)    
                        // 不采用这个压缩 严重影像画质
						/* uni.compressImage({
							src: res.tempFilePath,
							quality: plus.os.name == 'Android' ? 90 : 50,
							success: (results) => {
								// console.log(results.tempFilePath)
								this.$emit("getPhotoUrl", results.tempFilePath)
							}
						}) */
					},
					fail(res) {
						console.log(res)
					},
					complete() {
						uni.hideLoading()
					}
				}, this)
			},
			getDate() {
				var date = new Date()
				var y = date.getFullYear()
				var m = date.getMonth() + 1
				var d = date.getDate()
				var h = date.getHours()
				var minute = date.getMinutes()
				m = m < 10 ? "0" + m : m
				d = d < 10 ? "0" + d : d
				h = h < 10 ? "0" + h : h
				minute = minute < 10 ? "0" + minute : minute
				return y + "-" + m + "-" + d + " " + h + ":" + minute
			},
//保存本地
			saveFile(res) {
				let that = this;
				uni.saveFile({
					tempFilePath: res.tempFilePath || res.path,
					success: (res2) => {
						//图片列表获取
						that.imageList.push(res2.savedFilePath)
					},
					fail: () => {

					}
				})
			},
		}
	}
</script>

<style scoped>
	.createWaterMark {
		position: fixed;
		/* width: 200vw; */
		/* height: 200vh; */
		/* background-color: #000000; */
		z-index: 100000000;
		top: 0upx;
		left: 1000upx;
	}

	.createWaterMark_content {
		width: 200vw;
		position: absolute;
		top: 0upx;
		left: 0upx;
	}

	canvas {
		width: 100%;
		/* background-color: #000000; */
		height: 100%;
	}
</style>

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在uni-app中,您可以使用内置的相机组件`uni.chooseImage`来实现拍照功能,并使用`uni.uploadFile`来上传照片。下面是一个基本的示例代码: ```vue <template> <view> <button @click="takePhoto">拍照上传</button> <image :src="photoUrl" v-if="photoUrl" mode="aspectFit"></image> </view> </template> <script> export default { data() { return { photoUrl: '', // 存储拍照后的照片路径 }; }, methods: { takePhoto() { uni.chooseImage({ count: 1, // 最多可选择的图片数量 sourceType: ['camera'], // 选择图片的来源,这里设置为相机 success: (res) => { const tempFilePaths = res.tempFilePaths; this.photoUrl = tempFilePaths[0]; // 将拍照后的照片路径保存到data中 this.uploadPhoto(tempFilePaths[0]); // 上传照片 }, }); }, uploadPhoto(filePath) { uni.uploadFile({ url: 'http://your-upload-api-url', // 替换为您的上传接口地址 filePath, name: 'file', // 上传文件对应的字段名 formData: { // 可以添加额外的表单数据 // 如token、user_id等 }, success: (res) => { console.log(res); // 处理上传成功后的逻辑 }, fail: (error) => { console.log(error); // 处理上传失败的逻辑 }, }); }, }, }; </script> ``` 在上述示例中,我们在按钮的点击事件中调用`uni.chooseImage`方法,并设置`sourceType`为相机,以便从相机中获取照片。成功拍照后,会返回一个临时文件路径,我们将该路径保存到`photoUrl`变量中,并使用`image`组件来显示拍照后的照片。同时,我们调用了`uploadPhoto`方法来上传照片。 在`uploadPhoto`方法中,我们使用`uni.uploadFile`方法来进行上传操作。您需要将`url`替换为您的上传接口地址,并根据需要设置其他参数,如表单数据和文件对应的字段名。 请注意,示例中的代码仅供参考,您需要根据实际需求进行适当的修改和完善。 希望以上信息对您有所帮助!如果还有其他问题,请随时提问。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值