Skip to content

Image Processing API

Sharp provides rich image processing capabilities including resize, crop, rotate, filters and more operations.

Resize

Basic Usage

javascript
import sharp from 'sharp';

// Resize to specific dimensions
sharp('input.jpg')
  .resize(300, 200)
  .toFile('output.jpg');

// Specify width only, height auto-calculated
sharp('input.jpg')
  .resize(300)
  .toFile('output.jpg');

// Specify height only, width auto-calculated
sharp('input.jpg')
  .resize(null, 200)
  .toFile('output.jpg');

Resize Options

javascript
sharp('input.jpg')
  .resize(300, 200, {
    // Resize algorithm
    kernel: sharp.kernel.lanczos3,

    // Position
    position: 'center',

    // Background color
    background: { r: 255, g: 255, b: 255, alpha: 1 },

    // Maintain aspect ratio
    fit: 'cover',

    // Don't enlarge
    withoutEnlargement: true,

    // Don't reduce
    withoutReduction: false
  })
  .toFile('output.jpg');

Resize Algorithms

javascript
// Available resize algorithms
sharp.kernel.nearest      // Nearest neighbor
sharp.kernel.cubic        // Cubic interpolation
sharp.kernel.mitchell     // Mitchell-Netravali
sharp.kernel.lanczos2     // Lanczos 2-lobed
sharp.kernel.lanczos3     // Lanczos 3-lobed (default)

Fit Modes

javascript
// cover: Maintain aspect ratio, crop excess
sharp('input.jpg').resize(300, 200, { fit: 'cover' })

// contain: Maintain aspect ratio, add background
sharp('input.jpg').resize(300, 200, { fit: 'contain' })

// fill: Stretch to exact dimensions
sharp('input.jpg').resize(300, 200, { fit: 'fill' })

// inside: Maintain aspect ratio, don't exceed original size
sharp('input.jpg').resize(300, 200, { fit: 'inside' })

// outside: Maintain aspect ratio, at least reach specified size
sharp('input.jpg').resize(300, 200, { fit: 'outside' })

Crop (extract)

javascript
// Crop specific region
sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 300, height: 200 })
  .toFile('output.jpg');

// Crop and resize
sharp('input.jpg')
  .extract({ left: 100, top: 100, width: 300, height: 200 })
  .resize(150, 100)
  .toFile('output.jpg');

Rotate

javascript
// Rotate 90 degrees
sharp('input.jpg')
  .rotate(90)
  .toFile('output.jpg');

// Rotate with background color
sharp('input.jpg')
  .rotate(45, { background: { r: 255, g: 255, b: 255, alpha: 1 } })
  .toFile('output.jpg');

Flip/Flop

javascript
// Vertical flip
sharp('input.jpg')
  .flip()
  .toFile('output.jpg');

// Horizontal flip
sharp('input.jpg')
  .flop()
  .toFile('output.jpg');

Blur

javascript
// Gaussian blur
sharp('input.jpg')
  .blur(5)
  .toFile('output.jpg');

// Sharpen
sharp('input.jpg')
  .sharpen()
  .toFile('output.jpg');

// Custom sharpen parameters
sharp('input.jpg')
  .sharpen({
    sigma: 1,
    flat: 1,
    jagged: 2
  })
  .toFile('output.jpg');

Filters

Grayscale

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

Negate

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

Gamma Correction

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

Brightness/Contrast

javascript
sharp('input.jpg')
  .modulate({
    brightness: 1.2,    // Brightness (0.1-2.0)
    saturation: 0.8,    // Saturation (0-2.0)
    hue: 180            // Hue (0-360)
  })
  .toFile('output.jpg');

Color Operations

Tint

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

Color Matrix

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

Channel Operations

Separate Channels

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

// Get all channels
const channels = await sharp('input.jpg').separate();

Join Channels

javascript
// Merge from separate channel files
sharp('red.jpg')
  .joinChannel(['green.jpg', 'blue.jpg'])
  .toFile('merged.jpg');

Composite Operations

javascript
// Chain operations
sharp('input.jpg')
  .resize(800, 600)
  .rotate(90)
  .blur(2)
  .sharpen()
  .jpeg({ quality: 80 })
  .toFile('output.jpg');

Performance Optimization

Stream Processing

javascript
const fs = require('fs');

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

Batch Processing

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

Error Handling

javascript
try {
  await sharp('input.jpg')
    .resize(300, 200)
    .toFile('output.jpg');
} catch (error) {
  console.error('Image processing failed:', error.message);
}

Released under the Apache 2.0 License.