Skip to content

API Reference

Sharp provides a rich API for image processing. This page offers detailed reference for all available methods.

Constructor

sharp(input, options?)

Creates a new Sharp instance.

javascript
import sharp from 'sharp';

// Create from file
const image = sharp('input.jpg');

// Create from Buffer
const image = sharp(buffer);

// Create from Stream
const image = sharp(stream);

// Create blank image
const image = sharp({
  create: {
    width: 300,
    height: 200,
    channels: 4,
    background: { r: 255, g: 0, b: 0, alpha: 1 }
  }
});

Input Metadata

metadata()

Retrieves image metadata information.

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()

Retrieves image statistics.

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

Output Options

toFile(filename, callback?)

Saves the processed image to a file.

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

toBuffer(options?, callback?)

Outputs the processed image as a Buffer.

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

toFormat(format, options?)

Sets the output format.

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

Image Resizing

resize(width?, height?, options?)

Resizes the image.

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

// Maintain aspect ratio
await sharp('input.jpg')
  .resize(300, null)
  .toFile('output.jpg');

// Use fit modes
await sharp('input.jpg')
  .resize(300, 200, {
    fit: 'cover',        // Crop to fit
    position: 'center',  // Center crop
    background: { r: 255, g: 255, b: 255, alpha: 1 }
  })
  .toFile('output.jpg');

// Use kernel
await sharp('input.jpg')
  .resize(300, 200, {
    kernel: sharp.kernel.lanczos3
  })
  .toFile('output.jpg');

extract(region)

Crops an image region.

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

trim(threshold?)

Automatically trims transparent or white edges.

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

Image Operations

rotate(angle, options?)

Rotates the image.

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

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

flip(flip?)

Flips the image vertically.

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

flop(flop?)

Flops the image horizontally.

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

affine(matrix, options?)

Applies affine transformation.

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

Filter Effects

blur(sigma?)

Applies Gaussian blur.

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

sharpen(sigma?, flat?, jagged?)

Applies sharpening filter.

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

// Custom sharpen parameters
await sharp('input.jpg')
  .sharpen(1, 1, 2)
  .toFile('sharpened.jpg');

median(size?)

Applies median filter.

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

flatten(options?)

Flattens the alpha channel.

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

Color Operations

grayscale(grayscale?)

Converts to grayscale.

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

negate(negate?)

Applies negative effect.

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

modulate(options?)

Adjusts brightness, saturation, and hue.

javascript
await sharp('input.jpg')
  .modulate({
    brightness: 1.2,    // Brightness
    saturation: 0.8,    // Saturation
    hue: 90             // Hue
  })
  .toFile('modulated.jpg');

tint(rgb)

Applies tint.

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

removeAlpha()

Removes alpha channel.

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

ensureAlpha()

Ensures alpha channel exists.

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

Channel Operations

bandbool(boolean)

Applies boolean operations on channels.

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

joinChannel(channels)

Joins channels.

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

extractChannel(channel)

Extracts a single channel.

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

Global Properties

sharp.versions

Gets version information.

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

sharp.format

Gets supported formats.

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

sharp.kernel

Gets available kernels.

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

Error Handling

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

Performance Optimization

Stream Processing

javascript
const pipeline = sharp()
  .resize(300, 200)
  .jpeg({ quality: 80 });

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

Concurrent Processing

javascript
const promises = images.map(image =>
  sharp(image)
    .resize(300, 200)
    .jpeg()
    .toBuffer()
);

const results = await Promise.all(promises);

Complete Example

javascript
import sharp from 'sharp';

async function processImage() {
  try {
    // Get metadata
    const metadata = await sharp('input.jpg').metadata();
    console.log('Original image size:', metadata.width, 'x', metadata.height);

    // Create multiple versions
    const promises = [
      // Thumbnail
      sharp('input.jpg')
        .resize(150, 150, { fit: 'cover' })
        .jpeg({ quality: 90 })
        .toFile('thumbnail.jpg'),

      // Medium size
      sharp('input.jpg')
        .resize(800, 600, { fit: 'inside' })
        .webp({ quality: 80 })
        .toFile('medium.webp'),

      // Large size
      sharp('input.jpg')
        .resize(1920, 1080, { fit: 'inside' })
        .jpeg({ quality: 85, progressive: true })
        .toFile('large.jpg'),

      // Grayscale version
      sharp('input.jpg')
        .grayscale()
        .jpeg({ quality: 80 })
        .toFile('grayscale.jpg')
    ];

    await Promise.all(promises);
    console.log('All image processing completed!');
  } catch (error) {
    console.error('Processing failed:', error);
  }
}

processImage();

Next Steps

Released under the Apache 2.0 License.