Skip to content
jshacks.dev
Node.js

How to Resize Images in Node.js With sharp

Resize images in Node.js with sharp: set width and height, pick a fit mode, avoid upscaling, fix EXIF rotation and convert to WebP or AVIF in one pipeline.

7 min read
Summarize in AI
Flat illustration of a request passing through layers of middleware, with the Node.js, Cloudflare and Fastify logos.

Resizing an image sounds like a one-liner, and with sharp it nearly is. The trouble starts with the choices hidden behind that one line: what happens when the target shape differs from the original, whether a small image should be enlarged, why a phone photo comes out sideways, and which output format to ship. The wrong default on any of those gives you stretched faces, blurry thumbnails or a gallery where half the pictures lie on their sides. This post covers sharp 0.34 on Node.js 26, and every example here is written to be deterministic so the printed numbers are exact. You will see the basic resize, the five fit modes, withoutEnlargement, EXIF orientation, format conversion, and a small batch script that makes several sizes per file.

Installing and the first resize

sharp wraps the libvips image library and ships prebuilt binaries for the common platforms, so npm install sharp normally needs no compiler. It is fast because libvips streams pixels in small tiles instead of decoding the whole image into memory first, which is also why a large photo does not spike your heap the way a pure-JavaScript decoder would.

resize-basic.mjsJavaScript
import sharp from "sharp";

const info = await sharp("photo.jpg")
  .resize({ width: 800 })
  .toFile("photo-800.jpg");

console.log(info.format, info.width, info.height);

Suppose photo.jpg is 1600 by 1000 pixels. When you give only one dimension, sharp keeps the aspect ratio and computes the other, so the result is 800 by 500.

Text
jpeg 800 500

The toFile call resolves with an object describing what was written: format, width, height, channels and size in bytes. Printing only the fields you care about keeps the log readable, and it is a cheap way to assert in a test that the output is the shape you expect.

Always await the pipeline. A sharp chain is lazy. Nothing happens until you call toFile, toBuffer or pipe it as a stream, and a missing await in a loop gives you a script that exits before the files exist.

Width, height and the fit option

When you pass both width and height, the source rarely matches that box, and fit decides what gives. The default is cover.

fitBehaviorOutput size
coverfill the box, crop the overflowexactly width by height
containfit inside the box, pad the restexactly width by height
fillstretch to the box, ignore the ratioexactly width by height
insidefit inside the box, keep the ratioat most width by height
outsidecover the box, keep the ratioat least width by height

The difference is easiest to see with numbers. Take the same 1600 by 1000 source and a 300 by 300 box.

fit-modes.mjsJavaScript
import sharp from "sharp";

for (const fit of ["cover", "contain", "fill", "inside", "outside"]) {
  const info = await sharp("photo.jpg")
    .resize({ width: 300, height: 300, fit })
    .toBuffer({ resolveWithObject: true })
    .then(({ info }) => info);
  console.log(fit.padEnd(8), info.width, "x", info.height);
}
Text
cover    300 x 300
contain  300 x 300
fill     300 x 300
inside   300 x 188
outside  480 x 300

inside scales 1600 by 1000 down until the long side is 300, which gives 300 by 187.5, and sharp rounds that to 188. outside scales until the short side is 300, giving 480 by 300. The first three always return the exact box, but they get there differently: cover crops, contain adds borders, and fill distorts.

For thumbnails you almost always want cover, and you can choose what survives the crop with position. The default is the center, but position: "attention" makes sharp crop around the most detailed region, and position: "top" keeps the head of a portrait.

thumbnail.mjsJavaScript
import sharp from "sharp";

await sharp("portrait.jpg")
  .resize({ width: 200, height: 200, fit: "cover", position: "attention" })
  .toFile("avatar.jpg");
console.log("avatar written");
Text
avatar written

For product photos on a white background, contain with a background color keeps the whole item visible.

contain-pad.mjsJavaScript
import sharp from "sharp";

await sharp("product.png")
  .resize({
    width: 600,
    height: 600,
    fit: "contain",
    background: { r: 255, g: 255, b: 255, alpha: 1 },
  })
  .toFile("product-600.png");
console.log("padded");
Text
padded

Without a background, the padding is transparent for formats that support alpha and black for those that do not, and a black frame around a product photo is a bug report waiting to happen.

Do not enlarge small images

A resize to 800 pixels wide is a reduction for a 1600 pixel photo and an enlargement for a 400 pixel one. Enlarging invents pixels, so the result is soft, and the file grows with no gain in detail. Pass withoutEnlargement and sharp leaves small sources alone.

no-upscale.mjsJavaScript
import sharp from "sharp";

const info = await sharp("small.jpg")
  .resize({ width: 800, withoutEnlargement: true })
  .toBuffer({ resolveWithObject: true })
  .then(({ info }) => info);

console.log(info.width, info.height);

If small.jpg is 400 by 250, the output keeps its size.

Text
400 250

Make this the default in any upload pipeline. A user who uploads a 300 pixel avatar should get a 300 pixel avatar, not a blurry 800 pixel one that costs more to store and serve.

Phone photos come out sideways

Cameras usually store the pixels as the sensor saw them and record the intended rotation in an EXIF Orientation tag. Browsers honor that tag, so the photo looks right on screen. But when sharp writes a new file it drops the metadata by default, and the pixels now display in their raw sensor order. The result is a portrait photo lying on its side.

The fix is .rotate() with no arguments, which reads the orientation tag, rotates the pixels to match and clears the tag.

auto-rotate.mjsJavaScript
import sharp from "sharp";

const info = await sharp("phone.jpg")
  .rotate()
  .resize({ width: 600 })
  .toBuffer({ resolveWithObject: true })
  .then(({ info }) => info);

console.log(info.width, info.height);

For a portrait photo stored as 4000 by 3000 pixels with an orientation that means a quarter turn, the rotated image is 3000 by 4000, and resizing to 600 wide gives 600 by 800.

Text
600 800

Call rotate() before resize(), so the width you ask for applies to the picture as people see it. If you put them the other way round, a sideways source is resized by its sensor width and you get the wrong dimensions.

Choosing the output format

The output format follows the file extension in toFile, or an explicit method such as .webp() or .avif(). Each takes quality options.

formats.mjsJavaScript
import sharp from "sharp";

const pipeline = sharp("photo.jpg").rotate().resize({ width: 1200 });

await pipeline.clone().jpeg({ quality: 80, mozjpeg: true }).toFile("out.jpg");
await pipeline.clone().webp({ quality: 80 }).toFile("out.webp");
await pipeline.clone().avif({ quality: 50 }).toFile("out.avif");

console.log("three formats written");
Text
three formats written

clone() lets one decoded input feed several outputs, so you decode the source once. The quality numbers are not comparable across formats: 80 in WebP and 50 in AVIF are in the same neighborhood visually, not equal. Choose by looking at the files, and by what your readers' browsers support. WebP is supported everywhere current, AVIF costs noticeably more CPU to encode, so we would encode it in a background job and not inside a request handler.

Reading metadata first

Sometimes you need the size before you decide what to do, for instance to reject an image over a pixel limit.

metadata.mjsJavaScript
import sharp from "sharp";

const meta = await sharp("photo.jpg").metadata();
console.log(meta.format, meta.width, meta.height, meta.orientation);
Text
jpeg 1600 1000 undefined

orientation is undefined when the file has no orientation tag. metadata() reads headers only, so it is cheap. Set limitInputPixels in the sharp options to refuse decompression bombs, since a small file can declare a gigantic canvas. The default limit is generous, so lower it to match what your product needs.

A batch script for several sizes

A common job is producing a few widths for responsive images. Run them with a small concurrency limit and let sharp use its own thread pool.

batch.mjsJavaScript
import { readdir } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";

const widths = [400, 800, 1200];
const files = (await readdir("originals")).filter((f) => f.endsWith(".jpg"));

for (const file of files) {
  const name = path.parse(file).name;
  const input = sharp(path.join("originals", file)).rotate();
  await Promise.all(
    widths.map((w) =>
      input
        .clone()
        .resize({ width: w, withoutEnlargement: true })
        .webp({ quality: 80 })
        .toFile(path.join("out", `${name}-${w}.webp`)),
    ),
  );
  console.log(`${name}: ${widths.length} sizes`);
}

With two source files, a.jpg and b.jpg, the output is:

Text
a: 3 sizes
b: 3 sizes

Files are handled one after another and the three widths of each file run together, which keeps the number of open decoders small. Mind the output folder: toFile does not create out, so make it first with mkdir("out", { recursive: true }), or the first write fails with ENOENT.

Where the advice stops

sharp handles raster formats. It will rasterize an SVG at a size you choose, but it is not a vector editor, and animated GIF or WebP output needs the animated: true input option plus care with the page height. Very large batch jobs belong in a worker process, not in your web server, because even a fast encoder competes with request handling for CPU. Read the resize documentation for the options your version supports.

Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.