uniapp H5图片压缩封装

util.js 

// 图片压缩
export function getImageInfo(src, url) {

	uni.getImageInfo({
		src,
		success(res) {
			console.log('压缩前', res);
			let canvasWidth = res.width; //图片原始长宽
			let canvasHeight = res.height;
			let img = new Image();
			img.src = res.path;
			let canvas = document.createElement('canvas');
			let ctx = canvas.getContext('2d');
			// 这里根据要求限制图片宽高
			if (canvasWidth >= 1920) {
				canvas.width = 1600;
			} else {
				canvas.width = canvasWidth;
			}
			if (canvasHeight >= 1080) {
				canvas.height = 900;
			} else {
				canvas.height = canvasHeight;
			}
			ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
			//toBlob()方法创造Blob对象,用以展示canvas上的图片
			canvas.toBlob(function(fileSrc) {
				let imgSrc = window.URL.createObjectURL(fileSrc);
				console.log('压缩后', imgSrc);
				// 获取压缩后的图片地址,在进行上传
				upImg(imgSrc, url);
			});
		}
	});
}

function upImg(img, url) {

	uni.showLoading({
		title: '正在上传'
	});
	uni.uploadFile({
		url: url,
		filePath: img,
		fileType: 'image',
		name: 'file',
		formData: {
			num: 1
		},
		success: res => {
			console.log('img', img);
			console.log(res);
			uni.hideLoading()
			// 上传成功走自己的路基
		}
	});
}

main.js 

import * as img from "./common/utils/imgclose.js"
Vue.prototype.$img = img;

使用

chooseFrontId() {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['camera', 'album'], //这要注意,camera掉拍照,album是打开手机相册
					success: res => {
						this.choosedFrontIdSrc = res.tempFilePaths[0]
						// 选择图片后,调用获取图片信息方法,进行处理
						this.$img.getImageInfo(res.tempFilePaths[0],
							'/api/elec/peakValleyTimeSharingCustomer/uploadIdCard');
						
					}
				});

			},

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值