uniapp 图片压缩后上传

文章详细介绍了在uni-app中如何使用CompressorJS库来压缩图片,包括选择图片、压缩图片至Blob对象,然后通过FileReader将Blob对象转换回图片文件,最终上传压缩后的图片。主要方法包括`blobToFile`和`select`。
摘要由CSDN通过智能技术生成
<!-- 图片压缩 -->

<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>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值