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');
}
});
},