uniapp H5实现图片压缩限制在500KB内


有个问题就是如果传啥图片都压的话,会压缩过份,导致图片像素都没得了图片失真这些问题,最好限制一下图片size如果大于500KB这些再压

	uploadImg(field, item, index, val, key) {
				let imgurl
				let that = this
				if (val.value) {
					// that.formData[index].list[key].value = ''
					// that.formParams[field] = ''
					that.previewImg(field, item, index, val, key)
				} else if (field) {
					that.canvasParams.width = 0
					that.canvasParams.height = 0
					uni.chooseImage({
						count: 1,
						sizeType: ['compressed'], //H5不可用
						success(res) {
							if (res && res.tempFilePaths && res.tempFilePaths[0]) {
								const tempFilePaths = res.tempFilePaths[0]
								let base64
								uni.getImageInfo({
									src: tempFilePaths,
									success: function(res) {
										// uni.showLoading({
										// 	title: '加载中',
										// })
										console.log('压缩前', res)
										// that.sourceImg.push(res.path)
										let canvasWidth = res.width //图片原始长宽
										let canvasHeight = res.height
										let base = canvasWidth / canvasHeight
										if (canvasWidth > 5000) {
											canvasWidth = 5000;
											canvasHeight = Math.floor(canvasWidth / base)
										}
										let img = new Image()
										img.src = res.path
										let canvas = document.createElement('canvas');
										let ctx = canvas.getContext('2d')
										canvas.width = 200
										canvas.height = 200
										ctx.drawImage(img, 0, 0, 200, 200)
										canvas.toBlob(function(fileSrc) {
											let imgSrc = window.URL.createObjectURL(fileSrc)
											// that.totalImg.push(imgSrc)
											imgurl = imgSrc
											that.query.field = field
											that.query.index = index
											that.query.key = key
											// base64图片过大,三张图片一起上传超过10M会失败
											// that.setImg(res.tempFilePaths[0])
											// blob图片和实际图片大小一样
											if (that.query.index != -1 && that.query.key != -1) {
												// that.formData[that.query.index].list[that.query.key].value = res.tempFilePaths[0]
												that.formData[that.query.index].list[that.query.key].value = imgurl
											}
											// that.formParams[that.query.field] = res.tempFilePaths[0]
												that.formParams[that.query.field] = imgurl
											that.$emit('change', that.formParams)
											uni.hideLoading()
											// console.log(imgSrc, '压缩之后的图片路径')
										})
									}
								})
							}
						},
						fail(err) {
							uni.showToast({
								title: err.errMsg,
								icon: 'none'
							})
						},
					})
				}
			},

原创博主:uniapp上传多张图片 - SpongGirl - 博客园

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值