Ví dụ cơ bản
Đây là một số ví dụ sử dụng cơ bản của Sharp, giúp bạn nhanh chóng bắt đầu.
Thay đổi kích thước hình ảnh
Thay đổi kích thước đơn giản
javascript
import sharp from 'sharp';
// Thay đổi đến kích thước chỉ định
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');Giữ tỷ lệ khung hình
javascript
// Chỉ chỉ định chiều rộng, chiều cao tự động tính toán
await sharp('input.jpg')
.resize(300)
.toFile('output.jpg');
// Chỉ chỉ định chiều cao, chiều rộng tự động tính toán
await sharp('input.jpg')
.resize(null, 200)
.toFile('output.jpg');Chế độ phù hợp
javascript
// cover: Giữ tỷ lệ khung hình, cắt phần vượt quá
await sharp('input.jpg')
.resize(300, 200, { fit: 'cover' })
.toFile('output.jpg');
// contain: Giữ tỷ lệ khung hình, thêm nền
await sharp('input.jpg')
.resize(300, 200, { fit: 'contain', background: { r: 255, g: 255, b: 255 } })
.toFile('output.jpg');Chuyển đổi định dạng
JPEG sang PNG
javascript
await sharp('input.jpg')
.png()
.toFile('output.png');PNG sang JPEG
javascript
await sharp('input.png')
.jpeg({ quality: 80 })
.toFile('output.jpg');Chuyển đổi sang WebP
javascript
await sharp('input.jpg')
.webp({ quality: 80 })
.toFile('output.webp');Chuyển đổi sang AVIF
javascript
await sharp('input.jpg')
.avif({ quality: 80 })
.toFile('output.avif');Xoay hình ảnh
Xoay 90 độ
javascript
await sharp('input.jpg')
.rotate(90)
.toFile('output.jpg');Tự động xoay (theo EXIF)
javascript
await sharp('input.jpg')
.rotate() // Tự động xoay
.toFile('output.jpg');Lật hình ảnh
Lật dọc
javascript
await sharp('input.jpg')
.flip()
.toFile('output.jpg');Lật ngang
javascript
await sharp('input.jpg')
.flop()
.toFile('output.jpg');Cắt hình ảnh
Cắt vùng chỉ định
javascript
await sharp('input.jpg')
.extract({ left: 100, top: 100, width: 300, height: 200 })
.toFile('output.jpg');Cắt và thay đổi kích thước
javascript
await sharp('input.jpg')
.extract({ left: 100, top: 100, width: 300, height: 200 })
.resize(150, 100)
.toFile('output.jpg');Hiệu ứng bộ lọc
Chuyển đổi độ xám
javascript
await sharp('input.jpg')
.grayscale()
.toFile('output.jpg');Hiệu ứng làm mờ
javascript
await sharp('input.jpg')
.blur(5)
.toFile('output.jpg');Hiệu ứng làm sắc nét
javascript
await sharp('input.jpg')
.sharpen()
.toFile('output.jpg');Đảo ngược màu
javascript
await sharp('input.jpg')
.negate()
.toFile('output.jpg');Điều chỉnh màu
Điều chỉnh độ sáng
javascript
await sharp('input.jpg')
.modulate({ brightness: 1.2 })
.toFile('output.jpg');Điều chỉnh độ bão hòa
javascript
await sharp('input.jpg')
.modulate({ saturation: 0.8 })
.toFile('output.jpg');Điều chỉnh sắc độ
javascript
await sharp('input.jpg')
.modulate({ hue: 180 })
.toFile('output.jpg');Xử lý độ trong suốt
Thêm độ trong suốt
javascript
await sharp('input.jpg')
.ensureAlpha()
.png()
.toFile('output.png');Xóa độ trong suốt
javascript
await sharp('input.png')
.flatten({ background: { r: 255, g: 255, b: 255 } })
.jpeg()
.toFile('output.jpg');Thiết lập chất lượng
Chất lượng JPEG
javascript
// Chất lượng cao
await sharp('input.png')
.jpeg({ quality: 95 })
.toFile('output.jpg');
// Chất lượng trung bình
await sharp('input.png')
.jpeg({ quality: 80 })
.toFile('output.jpg');
// Chất lượng thấp (tệp nhỏ)
await sharp('input.png')
.jpeg({ quality: 50 })
.toFile('output.jpg');Chất lượng WebP
javascript
await sharp('input.jpg')
.webp({ quality: 80, lossless: false })
.toFile('output.webp');Thao tác chuỗi
Kết hợp nhiều thao tác
javascript
await sharp('input.jpg')
.resize(800, 600)
.rotate(90)
.blur(2)
.sharpen()
.jpeg({ quality: 80 })
.toFile('output.jpg');Xử lý có điều kiện
javascript
const image = sharp('input.jpg').resize(300, 200);
if (needsBlur) {
image.blur(3);
}
if (needsSharpen) {
image.sharpen();
}
await image.jpeg({ quality: 80 }).toFile('output.jpg');Xử lý lỗi
Xử lý lỗi cơ bản
javascript
try {
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');
} catch (error) {
console.error('Xử lý hình ảnh thất bại:', error.message);
}Kiểm tra tệp tồn tại
javascript
const fs = require('fs');
if (fs.existsSync('input.jpg')) {
await sharp('input.jpg')
.resize(300, 200)
.toFile('output.jpg');
} else {
console.error('Tệp đầu vào không tồn tại');
}Xử lý luồng
Đọc từ luồng
javascript
const fs = require('fs');
fs.createReadStream('input.jpg')
.pipe(sharp().resize(300, 200))
.pipe(fs.createWriteStream('output.jpg'));Đầu ra đến luồng
javascript
const fs = require('fs');
sharp('input.jpg')
.resize(300, 200)
.jpeg({ quality: 80 })
.pipe(fs.createWriteStream('output.jpg'));Xử lý Buffer
Tạo từ Buffer
javascript
const fs = require('fs');
const inputBuffer = fs.readFileSync('input.jpg');
const outputBuffer = await sharp(inputBuffer)
.resize(300, 200)
.jpeg({ quality: 80 })
.toBuffer();
fs.writeFileSync('output.jpg', outputBuffer);Đầu ra đến Buffer
javascript
const buffer = await sharp('input.jpg')
.resize(300, 200)
.jpeg({ quality: 80 })
.toBuffer();
// Có thể sử dụng buffer trực tiếp
console.log('Kích thước hình ảnh:', buffer.length);Xử lý hàng loạt
Xử lý tất cả hình ảnh trong thư mục
javascript
const fs = require('fs').promises;
const path = require('path');
async function processImages(inputDir, outputDir) {
const files = await fs.readdir(inputDir);
for (const file of files) {
if (file.match(/\.(jpg|jpeg|png|webp)$/i)) {
try {
await sharp(path.join(inputDir, file))
.resize(300, 200)
.jpeg({ quality: 80 })
.toFile(path.join(outputDir, file));
console.log(`Xử lý hoàn tất: ${file}`);
} catch (error) {
console.error(`Xử lý thất bại ${file}:`, error.message);
}
}
}
}
processImages('./input', './output');