h5端 上传图片太大压缩图片
由于uni.compressImage()不支持h5压缩图片,所以得自己写~
这个是html
<view class="camera" style="margin: 12rpx 0 31rpx 0;" >
<view class="bg-img" style="width: 202rpx;height: 202rpx;" v-for="(item,index) in imgList" :key="index" :data-url="imgList[index]">
<image :src="item" mode='aspectFill' style="width: 202rpx;height: 202rpx;"></image>
</view>
<view class="solids" style="width: 202rpx;height: 202rpx;display: flex;justify-content: center;align-items: center;" @tap="ChooseImage" v-if="imgList.length<1">
<image src="../../static/camera.png" mode="" class="camera_img"></image>
</view>
</view>
选择图片的方法
ChooseImage() {
uni.chooseImage({
count: 1, //默认9
sizeType: ['compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['camera'], //从相册选择
success: (res) => {
if (this.imgList.length != 0) {
this.imgList = this.imgList.concat(res.tempFilePaths)
} else {
this.imgList = res.tempFilePaths
}
let path = res.tempFilePaths[0]
let reader = new FileReader();
reader.readAsDataURL(res.tempFiles[0]);
let _this = this;
reader.onload = function() {
let content = path; //图片的src,base64格式
let img = new Image();
img.src = content;
img.onload = function() { //图片加载完毕
_this.compressEvent(img, (dataURL) => {
_this.uploadImg(dataURL); //这是上传图片的方法
})
}
};
}
});
},
compressEvent(img, callback) {
let canvasWidth = img.width //图片原始宽高
let canvasHeight = img.height;
//图片宽高比
let base = canvasWidth / canvasHeight;
//宽度最大设为1024
if (canvasWidth > 1024) {
canvasWidth = 1024;
canvasHeight = Math.floor(canvasWidth / base);
}
//绘制图像到画布
let canvas = document.createElement('canvas');
let ctx = canvas.getContext("2d");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
//将画布转为base64,mimeType类型为image/jpeg,图片质量为0.3
let dataURL = canvas.toDataURL("image/jpeg", 0.3);
callback ? callback(dataURL) : null; //调用回调函数
},
就完成啦~