Skip to content

Sharp Constructor

Sharp is a high-performance image processing library for Node.js. The constructor is the starting point for using Sharp.

Basic Usage

javascript
import sharp from 'sharp';

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

// Create Sharp instance from Buffer
const image = sharp(inputBuffer);

// Create Sharp instance from Stream
const image = sharp(inputStream);

Constructor Parameters

Input Sources

Sharp constructor accepts various input sources:

javascript
// File path
sharp('input.jpg')

// Buffer
sharp(buffer)

// Stream
sharp(stream)

// URL
sharp('https://example.com/image.jpg')

// Multiple input sources
sharp(['input1.jpg', 'input2.jpg'])

Options Object

javascript
sharp(input, {
  // Input options
  input: {
    failOnError: false,
    limitInputPixels: 268402689,
    sequentialRead: false
  },

  // Page options (for multi-page images)
  pages: -1,

  // Raw options
  raw: {
    width: 1920,
    height: 1080,
    channels: 3
  }
})

Input Options

failOnError

  • Type: boolean
  • Default: true
  • Description: Whether to throw an exception when encountering errors
javascript
sharp('input.jpg', { failOnError: false })
  .resize(300, 200)
  .toFile('output.jpg')
  .catch(err => console.log('Processing failed:', err));

limitInputPixels

  • Type: number
  • Default: 268402689 (16384 x 16384)
  • Description: Limit the number of pixels in input images
javascript
sharp('large-image.jpg', {
  limitInputPixels: 100000000
})

sequentialRead

  • Type: boolean
  • Default: false
  • Description: Whether to read image data sequentially
javascript
sharp('input.jpg', { sequentialRead: true })

Multi-page Images

For multi-page images (such as TIFF, PDF), you can specify which pages to process:

javascript
// Process all pages
sharp('multi-page.tiff', { pages: -1 })

// Process specific page (0-based)
sharp('multi-page.tiff', { pages: 0 })

// Process multiple pages
sharp('multi-page.tiff', { pages: [0, 2, 4] })

Raw Image Data

When processing raw image data, you need to specify dimensions and channel count:

javascript
sharp(rawBuffer, {
  raw: {
    width: 1920,
    height: 1080,
    channels: 3  // RGB
  }
})

Error Handling

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

Performance Tips

  1. Reuse Instances: Reuse Sharp instances whenever possible
  2. Stream Processing: Use stream processing for large files
  3. Memory Management: Release unused instances promptly
javascript
// Good practice
const sharp = require('sharp');
const image = sharp('input.jpg');

// Process multiple operations
await image
  .resize(300, 200)
  .jpeg({ quality: 80 })
  .toFile('output1.jpg');

await image
  .resize(150, 100)
  .png()
  .toFile('output2.jpg');

Released under the Apache 2.0 License.