Sharp: Fast Image Resizing and Conversion for Node.js

Sharp resizes, rotates and converts images in Node.js. It reads JPEG, PNG, WebP, GIF and SVG and writes WebP, AVIF and more. Code for each common task.

Images play a crucial role in building modern, fast, and user-friendly applications. Nearly every application makes use of images in some way or another.

Update: palette PNGs no longer need a custom libvips

Since sharp v0.28.0 (March 2021), the prebuilt binaries include libimagequant under a BSD license, so the note below about a globally installed libvips with GPL libimagequant no longer applies. PNG output is full color at 8 bits per pixel by default. Pass .png({ palette: true }) for smaller, indexed PNGs, or call .toColourspace('rgb16') for 16 bits per pixel. See the v0.28.0 changelog and the PNG output docs.

For example, users may want to resize their profile photos, and merchants often need to shape their images to make them as compelling as possible for buyers.

Large images can be frustrating since they take a long time to load and are challenging to store in a database. Fortunately, there’s a way to make images more user-friendly, load faster, and even appear in higher quality.

The typical use case for the Sharp library module is to convert large images in common formats to smaller, web-friendly JPEG, PNG, WebP, and AVIF images of varying dimensions, according to the official Sharp documentation.

Formats

The Sharp library is versatile in handling a wide range of image formats. It supports reading images in formats such as JPEG, PNG, WebP, TIFF, GIF, and SVG.

For output, Sharp can generate images in JPEG, PNG, WebP, AVIF, TIFF, and GIF formats, as well as provide uncompressed raw pixel data.

Sharp offers flexibility with input and output options, including Streams, Buffer objects, and the filesystem. You can even split a single input stream into multiple processing pipelines and output streams.

Additionally, Sharp can generate Deep Zoom image pyramids, making it ideal for use with “slippy map” tile viewers like OpenSeadragon.

Getting Started


Terminal window
yarn add sharp

Resizing Images

Let’s say we have a large image that takes forever to load. Instead of serving that big image, we should resize it appropriately, drastically reducing the load time of the application.

To resize images, Sharp only requires us to provide a path to the image, the new dimensions, and the output path for the newly resized image.

const sharp = require('sharp');
sharp('input.jpg')
.resize(500, 450)
.toFile('output.jpg', (err, info) => {
console.log(info);
});

This code resizes the original image to 500x450 dimensions.

Formatting Images

Changing the format of images is straightforward—simply chain functions together. The formatting has a .toFormat() function that takes the new format as the argument.

sharp('input.jpg')
.toFormat('png')
.toFile('output.png', (err, info) => {
console.log(info);
});

You can also set quality when converting to a specific format:

sharp('input.png')
.jpeg({ quality: 80 })
.toFile('output.jpg', (err, info) => {
console.log(info);
});

The quality specifier is an integer ranging from 1 to 100.

Once we run the code, an output.png file should appear in our project.

PNG output is always full-color at 8 or 16 bits per pixel. Indexed PNG input at 1, 2, or 4 bits per pixel is converted to 8 bits per pixel.

Some of these options require the use of a globally-installed libvips compiled with support for libimagequant (GPL), according to the Sharp official documentation.

Storing the Image in a Database

If you’re working with user profiles, you probably want to save the images in a database. Here’s how you can do that:

sharp('input.jpg')
.resize(500, 450)
.toBuffer()
.then(data => {
// store data in the database
})
.catch(err => {
console.error(err);
});

Notice how Sharp returns a promise instead of a callback. We can use that promise to perform actions when the image processing is done.

Async/Await Example

You can also use the async/await syntax instead of promises. Here’s an example:

async function processImage() {
try {
const data = await sharp('input.jpg')
.resize(500, 450)
.toBuffer();
// store data in the database
} catch (err) {
console.error(err);
}
}
processImage();

Rotating Images

Simple operations such as rotating images are easy with Sharp. Just call the rotate function with the number of degrees you want to rotate the image.

sharp('input.jpg')
.rotate(180)
.toFile('output.jpg', (err, info) => {
console.log(info);
});

You can also chain .flip().flop() if you want to rotate your image 180 degrees. flip mirrors the image vertically and flop mirrors it horizontally, so together they produce the same output as above.


Trevor I. Lasn

Trevor I. Lasn

Tech executive with over a decade of experience programming and building products. Building 0xinsider.com, ceodumps.com and whiteheap.com.



Related Articles

Check out these related articles that might be useful for you. They cover similar topics and provide additional insights.

Node.js
7 min read

Express 5.0 shipped on October 15, 2024, and 5.1.0 is now the npm default. Removed methods, new path matching, async error handling and Node.js 18+.

Sep 16, 2024
Read article
Node.js
7 min read

setImmediate runs after I/O, setTimeout(0) runs after the timer phase. Here's when to use each, with event loop diagrams.

Sep 8, 2024
Read article
Node.js
4 min read

Corepack pins the yarn or pnpm version a project uses through packageManager in package.json. Bundled through Node.js 24; on Node.js 25, install it from npm.

Nov 19, 2024
Read article
Security
4 min read

HTTP CONNECT asks a proxy to open a TCP tunnel to a host, so HTTPS passes through still encrypted. How the method works, a Node.js client, and common pitfalls.

Nov 28, 2024
Read article
Node.js
8 min read

This package compares your Node.js version against the Node.js Security Database, providing immediate feedback about potential security risks.

Jan 29, 2025
Read article
JavaScript
19 min read

Common causes of JavaScript memory leaks in Node.js and Deno, such as global objects and callbacks that hold large data, and how to profile heap usage.

Aug 10, 2024
Read article
Node.js
6 min read

Use AsyncLocalStorage to carry request IDs, user context, and tracing data through async calls without passing them as arguments.

Dec 20, 2024
Read article
React
5 min read

Split a React app's bundle with React.lazy and Suspense, lazy-load routes and CSS, and improve Core Web Vitals, which Google uses as a ranking factor.

Dec 26, 2023
Read article
CSS
7 min read

The CSSOM, or CSS Object Model, is the browser's map of every style rule. How it is built beside the DOM, how it computes styles, and how to keep it fast.

Oct 25, 2024
Read article

This article was originally published on https://www.trevorlasn.com/blog/sharp-high-performance-node-js-image-processing-library. It was written by a human and polished using grammar tools for clarity.