<!-- 图片压缩 -->
<template>
<view class="box">
<el-button style="margin-left: 10px;" size="small" type="success" @click="select">选择图片</el-button>
</view>
</template>
<script>
import Compressor from 'compressorjs'
export default {
data() {
return {
imgUrl: '',
fileList: [{
name: 'food.jpeg',
url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
}],
my_file: {}
};
},
methods: {
// blob对象转图片文件对象
blobToFile(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function() {
const dataUrl = reader.result;
const mime = dataUrl.split(",")[0].split(":")[1].split(";")[0];
let binary = atob(dataUrl.split(",")[1]);
let array = [];
for (let i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
const file = new File([new Uint8Array(array)], blob.name, {
type: mime
});
resolve(file);
};
reader.onerror = function() {
reject("Failed to convert blob to file.");
};
reader.readAsDataURL(blob);
});
},
// 选择图片
select() {
let that = this
let img_yasuo = ''
uni.chooseImage({
success: (res) => {
// 拿到选择的图片数组中第一张图片
console.log(res.tempFiles[0]);
// Compressor这个库压缩后,结果是blob对象
new Compressor(res.tempFiles[0], {
// 压缩质量
quality: 0.6,
success: (result) => {
console.log(result);
// blob对象转图片文件
this.blobToFile(result).then(file=>{
img_yasuo = file
// 拿到blob对象转换的图片地址
// 将图片地址添加到图片文件对象中
img_yasuo.path = URL.createObjectURL(result)
console.log('压缩后的图片文件对象', img_yasuo)
// TODO 上传图片
})
},
error: (err) => {
console.log('图片压缩失败', err.message)
}
})
}
})
},
}
}
</script>
<style lang="scss">
.box {
padding: 20rpx;
}
</style>
uniapp 图片压缩后上传
于 2023-05-07 20:10:15 首次发布
文章详细介绍了在uni-app中如何使用CompressorJS库来压缩图片,包括选择图片、压缩图片至Blob对象,然后通过FileReader将Blob对象转换回图片文件,最终上传压缩后的图片。主要方法包括`blobToFile`和`select`。
摘要由CSDN通过智能技术生成