js实现缩略图
使用 Canvas 实现缩略图
通过 Canvas 的 drawImage 方法缩放图片并生成缩略图。将原始图片绘制到缩小后的 Canvas 上,再转换为 Base64 或 Blob 数据。
function createThumbnail(file, maxWidth, maxHeight) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
// 计算缩放比例
if (width > maxWidth) {
height = Math.round((height * maxWidth) / width);
width = maxWidth;
}
if (height > maxHeight) {
width = Math.round((width * maxHeight) / height);
height = maxHeight;
}
// 绘制缩略图
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
// 转换为 Blob
canvas.toBlob(resolve, 'image/jpeg', 0.7);
};
img.src = URL.createObjectURL(file);
});
}
使用第三方库(如 sharp.js)
在 Node.js 环境中,可使用 sharp 库高效处理图片缩略图。需先安装库:npm install sharp。
const sharp = require('sharp');
async function generateThumbnail(inputPath, outputPath, width, height) {
await sharp(inputPath)
.resize(width, height, { fit: 'inside' })
.toFile(outputPath);
}
纯前端缩略图预览
通过 URL.createObjectURL 实现上传前的本地预览,适合不要求高质量缩略图的场景。
function previewThumbnail(file, targetElementId) {
const reader = new FileReader();
reader.onload = (e) => {
const img = document.createElement('img');
img.src = e.target.result;
img.style.maxWidth = '200px';
document.getElementById(targetElementId).appendChild(img);
};
reader.readAsDataURL(file);
}
响应式缩略图(CSS 方案)
利用 CSS 的 object-fit 属性实现容器内自适应缩略图,不改变原始文件。
<div class="thumbnail-container">
<img src="original.jpg" class="thumbnail" />
</div>
<style>
.thumbnail-container {
width: 200px;
height: 150px;
overflow: hidden;
}
.thumbnail {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
服务端生成缩略图(Node.js + Jimp)
使用 Jimp 库处理图片,适合需要后端处理的场景。
const Jimp = require('jimp');
async function createThumbnail(inputPath, outputPath) {
const image = await Jimp.read(inputPath);
await image
.resize(200, Jimp.AUTO)
.quality(80)
.writeAsync(outputPath);
}






