Skip to content

API Xử lý hình ảnh ​

Sharp cung cấp các chức năng xử lý hình ảnh phong phú, bao gồm thay đổi kích thước, cắt, xoay, bộ lọc và các thao tác khác.

Thay đổi kích thước (resize) ​

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

javascript
import sharp from 'sharp';

// Thay đổi đến kích thước chỉ định
sharp('input.jpg')
  .resize(300, 200)
  .toFile('output.jpg');

// Chỉ chỉ định chiều rộng, chiều cao tự động tính toán
sharp('input.jpg')
  .resize(300)
  .toFile('output.jpg');

// Chỉ chỉ định chiều cao, chiều rộng tự động tính toán
sharp('input.jpg')
  .resize(null, 200)
  .toFile('output.jpg');

Tùy chọn điều chỉnh ​

javascript
sharp('input.jpg')
  .resize(300, 200, {
    // Thuật toán điều chỉnh
    kernel: sharp.kernel.lanczos3,
    
    // Vị trí
    position: 'center',
    
    // Màu nền
    background: { r: 255, g: 255, b: 255, alpha: 1 },
    
    // Có giữ tỷ lệ khung hình không
    fit: 'cover',
    
    // Có không phóng to không
    withoutEnlargement: true,
    
    // Có không thu nhỏ không
    withoutReduction: false
  })
  .toFile('output.jpg');

Thuật toán điều chỉnh ​

javascript
// Các thuật toán điều chỉnh có sẵn
sharp.kernel.nearest      // Lân cận gần nhất
sharp.kernel.cubic        // Nội suy bậc ba
sharp.kernel.mitchell     // Mitchell-Netravali
sharp.kernel.lanczos2     // Lanczos 2-lobed
sharp.kernel.lanczos3     // Lanczos 3-lobed (mặc định)

Chế độ phù hợp ​

javascript
// cover: Giữ tỷ lệ khung hình, cắt phần vượt quá
sharp('input.jpg').resize(300, 200, { fit: 'cover' })

// contain: Giữ tỷ lệ khung hình, thêm nền
sharp('input.jpg').resize(300, 200, { fit: 'contain' })

// fill: Kéo dãn đến kích thước chỉ định
sharp('input.jpg').resize(300, 200, { fit: 'fill' })

// inside: Giữ tỷ lệ khung hình, không vượt quá kích thước gốc
sharp('input.jpg').resize(300, 200, { fit: 'inside' })

// outside: Giữ tỷ lệ khung hình, ít nhất đạt kích thước chỉ định
sharp('input.jpg').resize(300, 200, { fit: 'outside' })

Cắt (extract) ​

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

// Cắt và thay đổi kích thước
sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 300, height: 200 })
  .resize(150, 100)
  .toFile('output.jpg');

Xoay (rotate) ​

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

// Xoay và chỉ định màu nền
sharp('input.jpg')
  .rotate(45, { background: { r: 255, g: 255, b: 255, alpha: 1 } })
  .toFile('output.jpg');

Lật (flip/flop) ​

javascript
// Lật dọc
sharp('input.jpg')
  .flip()
  .toFile('output.jpg');

// Lật ngang
sharp('input.jpg')
  .flop()
  .toFile('output.jpg');

Làm mờ (blur) ​

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

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

// Tham số làm sắc nét tùy chỉnh
sharp('input.jpg')
  .sharpen({
    sigma: 1,
    flat: 1,
    jagged: 2
  })
  .toFile('output.jpg');

Bộ lọc (filters) ​

Độ xám ​

javascript
sharp('input.jpg')
  .grayscale()
  .toFile('output.jpg');

Đảo ngược ​

javascript
sharp('input.jpg')
  .negate()
  .toFile('output.jpg');

Hiệu chỉnh gamma ​

javascript
sharp('input.jpg')
  .gamma(2.2)
  .toFile('output.jpg');

Độ sáng/Độ tương phản ​

javascript
sharp('input.jpg')
  .modulate({
    brightness: 1.2,    // Độ sáng (0.1-2.0)
    saturation: 0.8,    // Độ bão hòa (0-2.0)
    hue: 180            // Sắc độ (0-360)
  })
  .toFile('output.jpg');

Thao tác màu ​

Tách sắc độ ​

javascript
sharp('input.jpg')
  .tint({ r: 255, g: 0, b: 0 })
  .toFile('output.jpg');

Ma trận màu ​

javascript
sharp('input.jpg')
  .recomb([
    [0.3588, 0.7044, 0.1368],
    [0.2990, 0.5870, 0.1140],
    [0.0000, 0.0000, 1.0000]
  ])
  .toFile('output.jpg');

Thao tác kênh ​

Tách kênh ​

javascript
// Lấy kênh đỏ
sharp('input.jpg')
  .extractChannel('red')
  .toFile('red-channel.jpg');

// Lấy tất cả các kênh
const channels = await sharp('input.jpg').separate();

Hợp nhất kênh ​

javascript
// Hợp nhất từ các tệp kênh riêng biệt
sharp('red.jpg')
  .joinChannel(['green.jpg', 'blue.jpg'])
  .toFile('merged.jpg');

Thao tác kết hợp ​

javascript
// Thao tác chuỗi
sharp('input.jpg')
  .resize(800, 600)
  .rotate(90)
  .blur(2)
  .sharpen()
  .jpeg({ quality: 80 })
  .toFile('output.jpg');

Tối ưu hiệu suất ​

Xử lý luồng ​

javascript
const fs = require('fs');

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

Xử lý hàng loạt ​

javascript
const sharp = require('sharp');
const fs = require('fs').promises;

async function processImages() {
  const files = await fs.readdir('./images');
  
  const promises = files
    .filter(file => file.endsWith('.jpg'))
    .map(async file => {
      await sharp(`./images/${file}`)
        .resize(300, 200)
        .jpeg({ quality: 80 })
        .toFile(`./output/${file}`);
    });
    
  await Promise.all(promises);
}

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

Liên kết liên quan ​

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