uniapp 使用u-upload上传图片时压缩
时间: 2023-10-23 18:09:44 浏览: 67
在uniapp中使用u-upload上传图片时,可以通过以下方式进行压缩:
1. 使用HTML5的canvas对图片进行压缩
可以通过以下代码将图片压缩到指定大小:
```
<template>
<u-upload :before-upload="beforeUpload">
</u-upload>
</template>
<script>
export default {
methods: {
beforeUpload(file) {
return new Promise((resolve, reject) => {
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const img = new Image()
img.onload = () => {
const targetWidth = 800 // 设置目标宽度
const targetHeight = img.height * targetWidth / img.width // 计算目标高度
canvas.width = targetWidth
canvas.height = targetHeight
ctx.clearRect(0, 0, targetWidth, targetHeight)
ctx.drawImage(img, 0, 0, targetWidth, targetHeight)
canvas.toBlob((blob) => {
resolve(new File([blob], file.name, { type: file.type }))
}, file.type, 0.7) // 0.7为压缩质量,可自行调整
}
img.src = URL.createObjectURL(file)
})
}
}
}
</script>
```
2. 使用第三方库进行压缩
可以使用第三方库如compressorjs等进行图片压缩,具体使用方法可以参考官方文档。
注意:压缩图片会影响图片质量,请根据实际需求选择合适的压缩方式和质量。