uni-app实现图片预览压缩上传:兼容h5+app,小程序等

场景:用户通过选取手机相册图片进行上传服务器,由于图片原始内存过大,造成上传缓慢等问题,前端实现前置按比例实现压缩上传。经测,效果还是很棒的。。。

view


	
	

js

export default{
    data() {
			return {
				// 画布大小
				canvasWidth: 375,
				canvasHeight: 667,
			}
	},
    methods: {
        //选择图片
			chooseImg() {
				uni.chooseImage({
						sizeType: ["compressed"],
						sourceType: ['camera', 'album'],
						success: (res) => {
							console.log(res)
							if (res.tempFilePaths.length > 0) {
								// this.imageUrl = res.tempFilePaths[0];
								// 图片压缩
								this.getImageInfo(res.tempFilePaths[0]);
							}
						},
					})
			},
        // 图片压缩
			getImageInfo(src) {
				let _this = this
				uni.getImageInfo({
					src,
					success(res) {
						console.log('压缩前', res)
						let canvasWidth = res.width //图片原始长宽
						let canvasHeight = res.height
						_this.canvasWidth = canvasWidth / 10
						_this.canvasHeight = canvasHeight / 10
						let canvas = uni.createCanvasContext('canvas');
						canvas.drawImage(src, 0, 0, canvasWidth / 10, canvasHeight / 10);
						canvas.draw(false, () => {
							uni.canvasToTempFilePath({
								canvasId: 'canvas', // canvas 标签的 id 或 canvas-id
								success: (ress) => {
									_this.imageUrl = ress.tempFilePath;
								}
							})
						})

					}
				})
			},
        submit(){

            // 接口上传
        }
    }
}

 

你可能感兴趣的:(uni-app,vue)