vue 图片上传压缩(vue+Vant+image-compressor)

图片压缩就是采用BASE64或者用cavas将图片重新渲染绘制,整合成指定大小或质量的图片上传到服务器。本文是基于Vant的Upload组件,结合image-compressor实现

一、安装image-compressor,在组件中引入

//安装
npm install image-compressor
//引入
import ImageCompressor from 'image-compressor.js'

二、Uploader组件

<van-uploader 
    :after-read="afterRead" 
    :before-delete="deletImg" 
    :before-read="onRead"
	:max-count="maxSize" 
    v-model="fileList" multiple
>
	<van-icon name="plus" />
</van-uploader>

 三、在图片上传前压缩图片,并转换为file格式

compressFile(file) {
	return new Promise((resolve, reject) => {
		new ImageCompressor(file, {
			quality: 0.6, //压缩质量
			checkOrientation: false, //图片翻转,默认为false
			success(result) {
				resolve(result);
			},
			error(e) {
				reject()
			}
		})
	})
},


async uploadMaterialImg(imgFile) {
	let This = this
	let file = await this.compressFile(imgFile)
	let formData = new FormData()
		formData.append('file', file)
	uploadMaterial(formData).then(res => {
		if (res.code == 200) {
			    This.fileList.push({
					isImage: true,
					id: res.data.ossId,
					url: res.data.ossUrl,
					ossNameNew: res.data.ossNameNew,
					imagePath: res.data.ossUrl,
					imageName: res.data.ossName,
					imageType: This.materialsObj.materialsType
				})
						
		} else {
				This.$toast(res.message)
		}
	}).catch(error => {
		This.$toast(error)
	})
}

关于image-compressor的文档说明,请移步:https://github.com/IronPans/img-compressor

在ios版本大于13时(navigator.userAgent获取版本号),拍照会翻转。可将checkOrientation: false设置为true

猜你喜欢

转载自blog.csdn.net/codingLeader/article/details/123330805