【前端】图片回显和压缩
时间: 2023-09-20 20:07:08 浏览: 47
对于图片回显,可以通过以下几种方式实现:
1. 使用<img>标签
使用<img>标签可以方便地将图片回显到页面上,例如:
```html
<img src="path/to/image.jpg" alt="image">
```
2. 使用canvas
使用canvas可以对图片进行一些处理,例如压缩、裁剪等操作,然后再将处理后的图片回显到页面上,例如:
```javascript
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL('image/jpeg');
const imgEl = document.createElement('img');
imgEl.src = dataURL;
document.body.appendChild(imgEl);
}
img.src = 'path/to/image.jpg';
```
对于图片压缩,可以使用canvas对图片进行压缩,例如:
```javascript
function compressImage(file, maxWidth, maxHeight, quality) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
const img = new Image();
img.src = this.result;
img.onload = function() {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
const dataURL = canvas.toDataURL('image/jpeg', quality);
resolve(dataURL);
}
}
reader.onerror = reject;
});
}
```
该函数接受四个参数:原始图片文件、最大宽度、最大高度、压缩质量(0-1之间的小数),返回一个Promise对象,resolve后的值为压缩后的图片DataURL。