High performance Node.js image processing

0.34.5 · active · verified Sat Apr 18

Sharp is a high-performance Node.js module designed for fast image processing, capable of resizing, cropping, and transforming JPEG, PNG, WebP, GIF, AVIF, and TIFF images. The current stable version is 0.34.5, and the library is actively maintained with regular updates and new features, often preceded by release candidates.

Common errors

Warnings

Install

Imports

Quickstart

Resizes an input image (or creates a placeholder if none exists) to 300x200 pixels, converts it to WebP format with 80% quality, and saves it to 'output.webp'.

import sharp from 'sharp';
import { createWriteStream, readFileSync } from 'fs';

async function processImage() {
  const inputPath = 'input.jpg'; // Replace with your input image path
  const outputPath = 'output.webp';

  // Create a dummy input image if it doesn't exist for demonstration
  try {
    readFileSync(inputPath);
  } catch (error) {
    const placeholderImage = Buffer.from('<svg width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="#f0f0f0" /><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="20" fill="#333">Hello</text></svg>');
    await sharp(placeholderImage)
      .toFile(inputPath);
    console.log(`Created dummy input.jpg at ${inputPath}`);
  }

  try {
    await sharp(inputPath)
      .resize(300, 200, { fit: 'cover' })
      .webp({ quality: 80 })
      .toFile(outputPath);
    console.log(`Image processed and saved to ${outputPath}`);
  } catch (error) {
    console.error(`Error processing image: ${error}`);
  }
}

processImage();

view raw JSON →