uniapp图片压缩的方法
时间: 2023-12-23 13:05:49 浏览: 111
Android一种高效压缩图片的方法
以下是uniapp中图片压缩的方法:
1. 使用HTML组件和JavaScript函数进行压缩:
```html
<template>
<compression-image ref="compressionImage"></compression-image>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
const compressionImage = ref(null);
const compressImage = async () => {
const url = await compressionImage.value.compress("这里传入需要压缩图片的路径", "这里传入图片大小", "这里传入图片的类型");
console.log(url, "这里就是压缩后的图片路径,传给后端就好啦!");
};
return {
compressionImage,
compressImage
};
}
};
</script>
```
2. 使用H5上传图片并压缩:
```html
<template>
<input type="file" accept="image/*" @change="uploadImage">
</template>
<script>
export default {
methods: {
uploadImage(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const image = new Image();
image.src = e.target.result;
image.onload = () => {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const maxWidth = 800; // 设置最大宽度
const maxHeight = 800; // 设置最大高度
let width = image.width;
let height = image.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
context.clearRect(0, 0, width, height);
context.drawImage(image, 0, 0, width, height);
canvas.toBlob((blob) => {
const formData = new FormData();
formData.append('file', blob, file.name);
// 发送formData到后端接口
// ...
}, file.type);
};
};
reader.readAsDataURL(file);
}
}
};
</script>
```
阅读全文