Skip to content

Bắt đầu nhanh

Hướng dẫn này sẽ giúp bạn nhanh chóng bắt đầu với Sharp và học các thao tác xử lý hình ảnh cơ bản.

Cách sử dụng cơ bản

Nhập Sharp

javascript
import sharp from 'sharp';

Hoặc sử dụng CommonJS:

javascript
const sharp = require('sharp');

Đọc hình ảnh

Sharp hỗ trợ nhiều định dạng đầu vào:

javascript
// Đọc từ tệp
const image = sharp('input.jpg');

// Đọc từ Buffer
const image = sharp(buffer);

// Đọc từ Stream
const image = sharp(stream);

Thao tác cơ bản

Thay đổi kích thước

javascript
// 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
await sharp('input.jpg')
  .resize(300, null) // Chiều rộng 300, chiều cao tự động
  .toFile('output.jpg');

// Sử dụng các chế độ phù hợp khác nhau
await sharp('input.jpg')
  .resize(300, 200, {
    fit: 'cover',    // Cắt để phù hợp
    position: 'center' // Cắt ở giữa
  })
  .toFile('output.jpg');

Chuyển đổi định dạng

javascript
// Chuyển đổi sang JPEG
await sharp('input.png')
  .jpeg({ quality: 80 })
  .toFile('output.jpg');

// Chuyển đổi sang WebP
await sharp('input.jpg')
  .webp({ quality: 80 })
  .toFile('output.webp');

// Chuyển đổi sang PNG
await sharp('input.jpg')
  .png({ compressionLevel: 9 })
  .toFile('output.png');

Cắt

javascript
// Cắt vùng chỉ định
await sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 200, height: 200 })
  .toFile('cropped.jpg');

Xoay

javascript
// Xoay 90 độ
await sharp('input.jpg')
  .rotate(90)
  .toFile('rotated.jpg');

Thao tác nâng cao

Hiệu ứng bộ lọc

javascript
// Làm mờ
await sharp('input.jpg')
  .blur(5)
  .toFile('blurred.jpg');

// Làm sắc nét
await sharp('input.jpg')
  .sharpen()
  .toFile('sharpened.jpg');

// Độ xám
await sharp('input.jpg')
  .grayscale()
  .toFile('grayscale.jpg');

Điều chỉnh màu sắc

javascript
// Điều chỉnh độ sáng
await sharp('input.jpg')
  .modulate({ brightness: 1.2 })
  .toFile('bright.jpg');

// Điều chỉnh độ tương phản
await sharp('input.jpg')
  .modulate({ contrast: 1.5 })
  .toFile('contrast.jpg');

// Điều chỉnh độ bão hòa
await sharp('input.jpg')
  .modulate({ saturation: 0.8 })
  .toFile('desaturated.jpg');

Tùy chọn đầu ra

Lưu vào tệp

javascript
await sharp('input.jpg')
  .resize(300, 200)
  .toFile('output.jpg');

Đầu ra đến Buffer

javascript
const buffer = await sharp('input.jpg')
  .resize(300, 200)
  .jpeg()
  .toBuffer();

Đầu ra đến Stream

javascript
sharp('input.jpg')
  .resize(300, 200)
  .jpeg()
  .pipe(fs.createWriteStream('output.jpg'));

Xử lý lỗi

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);
}

Tối ưu hiệu suất

Xử lý luồng

javascript
// Sử dụng luồng khi xử lý tệp lớn
const pipeline = sharp()
  .resize(300, 200)
  .jpeg({ quality: 80 });

fs.createReadStream('large-input.jpg')
  .pipe(pipeline)
  .pipe(fs.createWriteStream('output.jpg'));

Xử lý đồng thời

javascript
// Xử lý nhiều hình ảnh cùng lúc
const promises = images.map(image => 
  sharp(image)
    .resize(300, 200)
    .jpeg()
    .toBuffer()
);

const results = await Promise.all(promises);

Ví dụ đầy đủ

javascript
import sharp from 'sharp';
import fs from 'fs';

async function processImage() {
  try {
    // Tạo hình thu nhỏ
    await sharp('input.jpg')
      .resize(150, 150, { fit: 'cover' })
      .jpeg({ quality: 90 })
      .toFile('thumbnail.jpg');

    // Tạo hình ảnh kích thước trung bình
    await sharp('input.jpg')
      .resize(800, 600, { fit: 'inside' })
      .webp({ quality: 80 })
      .toFile('medium.webp');

    // Tạo hình ảnh kích thước lớn
    await sharp('input.jpg')
      .resize(1920, 1080, { fit: 'inside' })
      .jpeg({ quality: 85 })
      .toFile('large.jpg');

    console.log('Xử lý hình ảnh hoàn tất!');
  } catch (error) {
    console.error('Xử lý thất bại:', error);
  }
}

processImage();

Bước tiếp theo

Bây giờ bạn đã hiểu cách sử dụng cơ bản của Sharp, bạn có thể:

Được phát hành theo Giấy phép Apache 2.0.