js实现thumbnail
使用Canvas生成缩略图
通过Canvas的drawImage方法可以缩放图片并生成缩略图。
![]()
function generateThumbnail(file, width, height) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
resolve(canvas.toDataURL('image/jpeg'));
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
}
使用第三方库(如sharp-js)
Node.js环境下可使用sharp库高效处理图片缩略图。
![]()
const sharp = require('sharp');
async function createThumbnail(inputPath, outputPath, width, height) {
await sharp(inputPath)
.resize(width, height)
.toFile(outputPath);
}
纯CSS实现缩略图效果
通过CSS的object-fit和固定宽高实现视觉缩略图,不改变原始文件。
<style>
.thumbnail {
width: 150px;
height: 150px;
object-fit: cover;
}
</style>
<img src="original.jpg" class="thumbnail">
使用URL.createObjectURL预览
适用于上传前快速生成客户端缩略图预览。
function previewThumbnail(file) {
const url = URL.createObjectURL(file);
const img = document.createElement('img');
img.src = url;
img.style.width = '100px';
document.body.appendChild(img);
}
注意事项
- Canvas方法会损失部分画质,可通过
quality参数调整JPEG输出质量。 - 大文件处理时建议使用Web Worker避免阻塞主线程。
- 移动端需注意内存限制,建议分块处理或降低分辨率。






