有个问题就是如果传啥图片都压的话,会压缩过份,导致图片像素都没得了图片失真这些问题,最好限制一下图片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 - 博客园

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐