Skip to content

Tham chiếu API ​

Sharp cung cấp API phong phú để xử lý hình ảnh. Trang này cung cấp tham chiếu chi tiết về tất cả các phương thức có sẵn.

Hàm tạo ​

sharp(input, options?) ​

Tạo một instance Sharp mới.

javascript
import sharp from 'sharp';

// Tạo từ tệp
const image = sharp('input.jpg');

// Tạo từ Buffer
const image = sharp(buffer);

// Tạo từ Stream
const image = sharp(stream);

// Tạo hình ảnh trống
const image = sharp({
  create: {
    width: 300,
    height: 200,
    channels: 4,
    background: { r: 255, g: 0, b: 0, alpha: 1 }
  }
});

Siêu dữ liệu đầu vào ​

metadata() ​

Lấy thông tin siêu dữ liệu của hình ảnh.

javascript
const metadata = await sharp('input.jpg').metadata();
console.log(metadata);
// {
//   format: 'jpeg',
//   width: 1920,
//   height: 1080,
//   space: 'srgb',
//   channels: 3,
//   depth: 'uchar',
//   density: 72,
//   hasProfile: false,
//   hasAlpha: false
// }

stats() ​

Lấy thông tin thống kê của hình ảnh.

javascript
const stats = await sharp('input.jpg').stats();
console.log(stats);
// {
//   isOpaque: true,
//   dominant: { r: 128, g: 128, b: 128 }
// }

Tùy chọn đầu ra ​

toFile(filename, callback?) ​

Lưu hình ảnh đã xử lý vào tệp.

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

toBuffer(options?, callback?) ​

Đầu ra hình ảnh đã xử lý dưới dạng Buffer.

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

toFormat(format, options?) ​

Thiết lập định dạng đầu ra.

javascript
// JPEG
await sharp('input.png')
  .jpeg({ quality: 80, progressive: true })
  .toFile('output.jpg');

// PNG
await sharp('input.jpg')
  .png({ compressionLevel: 9, adaptiveFiltering: true })
  .toFile('output.png');

// WebP
await sharp('input.jpg')
  .webp({ quality: 80, effort: 6 })
  .toFile('output.webp');

// AVIF
await sharp('input.jpg')
  .avif({ quality: 80, effort: 4 })
  .toFile('output.avif');

// TIFF
await sharp('input.jpg')
  .tiff({ quality: 80, compression: 'lzw' })
  .toFile('output.tiff');

Điều chỉnh hình ảnh ​

resize(width?, height?, options?) ​

Thay đổi kích thước hình ảnh.

javascript
// Điều chỉnh cơ bản
await sharp('input.jpg')
  .resize(300, 200)
  .toFile('output.jpg');

// Giữ tỷ lệ khung hình
await sharp('input.jpg')
  .resize(300, null)
  .toFile('output.jpg');

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

// Sử dụng kernel
await sharp('input.jpg')
  .resize(300, 200, {
    kernel: sharp.kernel.lanczos3
  })
  .toFile('output.jpg');

extract(region) ​

Cắt vùng hình ảnh.

javascript
await sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 200, height: 200 })
  .toFile('cropped.jpg');

trim(threshold?) ​

Tự động cắt các cạnh trong suốt hoặc trắng.

javascript
await sharp('input.png')
  .trim()
  .toFile('trimmed.png');

Thao tác hình ảnh ​

rotate(angle, options?) ​

Xoay hình ảnh.

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

// Xoay và điền nền
await sharp('input.jpg')
  .rotate(45, { background: { r: 255, g: 255, b: 255, alpha: 1 } })
  .toFile('rotated.jpg');

flip(flip?) ​

Lật hình ảnh theo chiều dọc.

javascript
await sharp('input.jpg')
  .flip()
  .toFile('flipped.jpg');

flop(flop?) ​

Lật hình ảnh theo chiều ngang.

javascript
await sharp('input.jpg')
  .flop()
  .toFile('flopped.jpg');

affine(matrix, options?) ​

Áp dụng biến đổi affine.

javascript
await sharp('input.jpg')
  .affine([[1, 0.3], [0, 1]], { background: { r: 255, g: 255, b: 255, alpha: 1 } })
  .toFile('transformed.jpg');

Hiệu ứng bộ lọc ​

blur(sigma?) ​

Áp dụng làm mờ Gaussian.

javascript
await sharp('input.jpg')
  .blur(5)
  .toFile('blurred.jpg');

sharpen(sigma?, flat?, jagged?) ​

Áp dụng bộ lọc làm sắc nét.

javascript
await sharp('input.jpg')
  .sharpen()
  .toFile('sharpened.jpg');

// Tham số làm sắc nét tùy chỉnh
await sharp('input.jpg')
  .sharpen(1, 1, 2)
  .toFile('sharpened.jpg');

median(size?) ​

Áp dụng bộ lọc trung vị.

javascript
await sharp('input.jpg')
  .median(3)
  .toFile('median.jpg');

flatten(options?) ​

Hợp nhất kênh trong suốt.

javascript
await sharp('input.png')
  .flatten({ background: { r: 255, g: 255, b: 255 } })
  .toFile('flattened.jpg');

Thao tác màu sắc ​

grayscale(grayscale?) ​

Chuyển đổi sang hình ảnh độ xám.

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

negate(negate?) ​

Hiệu ứng âm bản.

javascript
await sharp('input.jpg')
  .negate()
  .toFile('negated.jpg');

modulate(options?) ​

Điều chỉnh độ sáng, độ bão hòa và sắc độ.

javascript
await sharp('input.jpg')
  .modulate({
    brightness: 1.2,    // Độ sáng
    saturation: 0.8,    // Độ bão hòa
    hue: 90             // Sắc độ
  })
  .toFile('modulated.jpg');

tint(rgb) ​

Áp dụng màu nhuộm.

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

removeAlpha() ​

Xóa kênh trong suốt.

javascript
await sharp('input.png')
  .removeAlpha()
  .toFile('no-alpha.jpg');

ensureAlpha() ​

Đảm bảo có kênh trong suốt.

javascript
await sharp('input.jpg')
  .ensureAlpha()
  .toFile('with-alpha.png');

Thao tác kênh ​

bandbool(boolean) ​

Áp dụng phép toán boolean cho kênh.

javascript
await sharp('input.jpg')
  .bandbool('and')
  .toFile('bandbool.jpg');

joinChannel(channels) ​

Hợp nhất kênh.

javascript
await sharp('input.jpg')
  .joinChannel(['red.jpg', 'green.jpg', 'blue.jpg'])
  .toFile('joined.jpg');

extractChannel(channel) ​

Trích xuất một kênh đơn lẻ.

javascript
await sharp('input.jpg')
  .extractChannel('red')
  .toFile('red-channel.jpg');

Thuộc tính toàn cục ​

sharp.versions ​

Lấy thông tin phiên bản.

javascript
console.log(sharp.versions);
// {
//   sharp: '0.32.0',
//   vips: '8.14.0'
// }

sharp.format ​

Lấy các định dạng được hỗ trợ.

javascript
console.log(sharp.format);
// {
//   jpeg: { id: 'jpeg', ... },
//   png: { id: 'png', ... },
//   webp: { id: 'webp', ... },
//   ...
// }

sharp.kernel ​

Lấy các kernel có sẵn.

javascript
console.log(sharp.kernel);
// {
//   nearest: 'nearest',
//   cubic: 'cubic',
//   mitchell: 'mitchell',
//   lanczos2: 'lanczos2',
//   lanczos3: 'lanczos3'
// }

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
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
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';

async function processImage() {
  try {
    // Lấy siêu dữ liệu
    const metadata = await sharp('input.jpg').metadata();
    console.log('Kích thước hình ảnh gốc:', metadata.width, 'x', metadata.height);

    // Tạo nhiều phiên bản
    const promises = [
      // Hình thu nhỏ
      sharp('input.jpg')
        .resize(150, 150, { fit: 'cover' })
        .jpeg({ quality: 90 })
        .toFile('thumbnail.jpg'),

      // Kích thước trung bình
      sharp('input.jpg')
        .resize(800, 600, { fit: 'inside' })
        .webp({ quality: 80 })
        .toFile('medium.webp'),

      // Kích thước lớn
      sharp('input.jpg')
        .resize(1920, 1080, { fit: 'inside' })
        .jpeg({ quality: 85, progressive: true })
        .toFile('large.jpg'),

      // Phiên bản độ xám
      sharp('input.jpg')
        .grayscale()
        .jpeg({ quality: 80 })
        .toFile('grayscale.jpg')
    ];

    await Promise.all(promises);
    console.log('Tất cả hình ảnh đã được xử lý!');
  } catch (error) {
    console.error('Xử lý thất bại:', error);
  }
}

processImage();

Bước tiếp theo ​

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