Images

suggest change

Node.js has no built-in image API. Buffer and node:fs let you read image bytes, but decoding a JPEG, resizing it and encoding it as WebP needs a library. The standard choice is sharp, a wrapper around the C library libvips. It's fast, uses little memory and ships prebuilt binaries for Windows, macOS and Linux, so npm install doesn't need a compiler.

Task sharp API
read size, format, EXIF metadata(), stats()
resize, crop, thumbnails resize(), extract(), trim(), extend()
convert formats jpeg(), png(), webp(), avif(), gif(), toFormat()
rotate, flip, filters rotate(), autoOrient(), flip(), flop(), blur(), sharpen(), grayscale(), modulate()
watermarks, overlays, text composite(), SVG input, text input
pixel-level access raw() output, raw input option

The examples were run with Node.js 24, sharp 0.35 and express 5.3, in a project whose package.json has "type": "module":

npm install sharp express

Creating test images

sharp(input) accepts a file path, a Buffer, or an object describing a new image. It returns a pipeline: you chain operations, pick an output format and finish with toFile() or toBuffer(). Nothing happens until that last call, which returns a promise.

SVG is a convenient way to draw images in code, because sharp renders it like any other input format:

import sharp from 'sharp';

// a solid 400x300 orange image
await sharp({
  create: { width: 400, height: 300, channels: 3, background: '#ff8800' },
})
  .png()
  .toFile('orange.png');

// render an SVG into a 1200x800 photo-like JPEG
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800">
  <defs>
    <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0" stop-color="#1e3c72"/>
      <stop offset="1" stop-color="#2a5298"/>
    </linearGradient>
  </defs>
  <rect width="1200" height="800" fill="url(#sky)"/>
  <circle cx="900" cy="200" r="90" fill="#ffd700"/>
  <polygon points="0,800 350,350 700,800" fill="#2e8b57"/>
  <polygon points="400,800 800,300 1200,800" fill="#3cb371"/>
</svg>`;

const info = await sharp(Buffer.from(svg)).jpeg({ quality: 90 }).toFile('photo.jpg');
console.log(info);
{
  format: 'jpeg',
  width: 1200,
  height: 800,
  channels: 3,
  premultiplied: false,
  hasAlpha: false,
  size: 23719
}

toFile() picks the encoder from the file extension unless you call a format method such as .jpeg() or .png() explicitly. It resolves with an info object describing the output. The remaining examples use photo.jpg (blue sky, yellow sun, two green hills) and orange.png.

Reading metadata

metadata() only parses the file header, so it's cheap even for large images. stats() decodes the pixels and computes per-channel statistics:

import sharp from 'sharp';

const meta = await sharp('photo.jpg').metadata();
const { format, width, height, channels, space, density, hasAlpha, orientation } = meta;
console.log({ format, width, height, channels, space, density, hasAlpha, orientation });

const stats = await sharp('photo.jpg').stats();
console.log('dominant color:', stats.dominant);
console.log('is opaque:', stats.isOpaque);
console.log('red channel mean:', stats.channels[0].mean.toFixed(1));
{
  format: 'jpeg',
  width: 1200,
  height: 800,
  channels: 3,
  space: 'srgb',
  density: 72,
  hasAlpha: false,
  orientation: undefined
}
dominant color: { r: 40, g: 72, b: 136 }
is opaque: true
red channel mean: 47.1

orientation is the EXIF orientation tag, set by most phone cameras. It's undefined here because our generated JPEG has no EXIF data. See the section on EXIF orientation below.

Resizing

resize(width, height, options) scales an image. When both dimensions are given, the fit option decides what happens if the aspect ratio doesn't match:

import sharp from 'sharp';

const fits = ['cover', 'contain', 'fill', 'inside', 'outside'];

for (const fit of fits) {
  const info = await sharp('photo.jpg')
    .resize(300, 300, { fit, background: '#ffffff' })
    .toFile(`resized-${fit}.jpg`);
  console.log(`${fit.padEnd(8)} -> ${info.width}x${info.height}`);
}

// only one dimension: the other is computed from the aspect ratio
const w = await sharp('photo.jpg').resize({ width: 600 }).toBuffer({ resolveWithObject: true });
console.log('width 600   ->', `${w.info.width}x${w.info.height}`);

// never enlarge a small image
const small = await sharp('orange.png')
  .resize({ width: 1000, withoutEnlargement: true })
  .toBuffer({ resolveWithObject: true });
console.log('no enlarge  ->', `${small.info.width}x${small.info.height}`);
cover    -> 300x300
contain  -> 300x300
fill     -> 300x300
inside   -> 300x200
outside  -> 450x300
width 600   -> 600x400
no enlarge  -> 400x300

withoutEnlargement: true stops small images from being upscaled into a blurry mess.

Converting formats and choosing quality

Each format method takes encoder options. A sharp pipeline can only be run once, so clone() is used to encode the same resized image several ways:

import sharp from 'sharp';

const input = sharp('photo.jpg').resize({ width: 800 });

const outputs = {
  'jpeg q80': input.clone().jpeg({ quality: 80, mozjpeg: true }),
  'jpeg q50': input.clone().jpeg({ quality: 50, mozjpeg: true }),
  'png': input.clone().png({ compressionLevel: 9 }),
  'png palette': input.clone().png({ palette: true }),
  'webp q80': input.clone().webp({ quality: 80 }),
  'avif q50': input.clone().avif({ quality: 50 }),
};

for (const [name, pipeline] of Object.entries(outputs)) {
  const buf = await pipeline.toBuffer();
  console.log(`${name.padEnd(12)} ${String(buf.length).padStart(7)} bytes`);
}

// toFormat() picks the encoder from a string, e.g. from a query parameter
const { info } = await sharp('orange.png').toFormat('webp').toBuffer({ resolveWithObject: true });
console.log('toFormat:', info.format, info.size, 'bytes');
jpeg q80        8219 bytes
jpeg q50        5286 bytes
png            69833 bytes
png palette    29153 bytes
webp q80        5136 bytes
avif q50        3540 bytes
toFormat: webp 304 bytes

Rough guidelines:

Exact sizes depend heavily on content: these numbers come from a smooth, synthetic image, and real photos produce much larger files.

Cropping, rotating and filters

import sharp from 'sharp';

// crop a 400x300 region whose top-left corner is at (700, 50): the sun
await sharp('photo.jpg')
  .extract({ left: 700, top: 50, width: 400, height: 300 })
  .toFile('sun.jpg');

// rotate, flip (vertical) and flop (horizontal)
const r = await sharp('photo.jpg').rotate(90).toFile('rotated.jpg');
console.log('rotate(90):', `${r.width}x${r.height}`);
const r2 = await sharp('photo.jpg')
  .rotate(30, { background: '#ffffff' })
  .toFile('rotated30.jpg');
console.log('rotate(30):', `${r2.width}x${r2.height}`);
await sharp('photo.jpg').flop().toFile('mirrored.jpg');

// filters
await sharp('photo.jpg').grayscale().toFile('gray.jpg');
await sharp('photo.jpg').blur(8).toFile('blurred.jpg');
await sharp('photo.jpg').resize({ width: 300 }).sharpen().toFile('sharp.jpg');
await sharp('photo.jpg').modulate({ brightness: 1.2, saturation: 0.5 }).toFile('faded.jpg');
await sharp('photo.jpg').tint('#c08040').toFile('sepia.jpg');

// trim removes borders of a similar color
const padded = await sharp('orange.png')
  .extend({ top: 50, bottom: 50, left: 50, right: 50, background: '#ffffff' })
  .toBuffer();
const trimmed = await sharp(padded).trim().toBuffer({ resolveWithObject: true });
const pm = await sharp(padded).metadata();
console.log('padded:', `${pm.width}x${pm.height}`, 'trimmed:', `${trimmed.info.width}x${trimmed.info.height}`);
rotate(90): 800x1200
rotate(30): 1439x1293
padded: 500x400 trimmed: 400x300

Operations run in a fixed order chosen by sharp (for example, rotation before resizing), not in the order you chain them. To force a specific order, run one pipeline, take the result with toBuffer() and start a new pipeline from it, as the trim() example does.

EXIF orientation and metadata

Phone cameras usually store pixels in the sensor's orientation and add an EXIF tag saying how to rotate the image for display. Browsers honor the tag, but if you resize the image and drop the metadata, a portrait photo ends up sideways. Call autoOrient() before resizing anything that came from a camera:

import sharp from 'sharp';

// simulate a phone photo: pixels stored landscape, EXIF says "rotate 90° CW"
await sharp('photo.jpg')
  .withMetadata({ orientation: 6 })
  .toFile('phone.jpg');

const m = await sharp('phone.jpg').metadata();
console.log('stored:', `${m.width}x${m.height}`, 'orientation:', m.orientation);
console.log('displayed:', m.autoOrient);

// autoOrient() applies the EXIF rotation to the pixels and drops the tag
const out = await sharp('phone.jpg').autoOrient().resize({ width: 200 }).toBuffer();
const m2 = await sharp(out).metadata();
console.log('after autoOrient:', `${m2.width}x${m2.height}`, 'orientation:', m2.orientation);

// by default output has no EXIF/ICC metadata; keepMetadata() preserves it
const kept = await sharp('phone.jpg').keepMetadata().toBuffer();
const stripped = await sharp('phone.jpg').toBuffer();
console.log('exif bytes kept:', (await sharp(kept).metadata()).exif?.length);
console.log('exif bytes stripped:', (await sharp(stripped).metadata()).exif?.length);
stored: 1200x800 orientation: 6
displayed: { width: 800, height: 1200 }
after autoOrient: 200x300 orientation: undefined
exif bytes kept: 186
exif bytes stripped: undefined

By default sharp writes output without EXIF, XMP and ICC metadata. This is usually what you want for images you publish: EXIF can contain the GPS location where a photo was taken and the camera's serial number. Use keepMetadata() (or the narrower keepExif() and keepIccProfile()) only when you need to preserve it. Calling rotate() with no arguments is the older way of applying the EXIF orientation and still works.

Watermarks and text with composite()

composite() layers images on top of the base image. Each overlay can be a file path, a buffer (including SVG) or a raw pixel buffer, positioned with gravity ('northwest', 'center', 'southeast', ...) or with exact top and left coordinates:

import sharp from 'sharp';

// a semi-transparent text watermark drawn with SVG
const label = Buffer.from(`
<svg xmlns="http://www.w3.org/2000/svg" width="360" height="60">
  <rect width="360" height="60" rx="10" fill="black" fill-opacity="0.5"/>
  <text x="180" y="40" font-family="sans-serif" font-size="28"
        fill="white" text-anchor="middle">© Example Photos</text>
</svg>`);

// a round 120x120 "logo" with transparency
const logo = await sharp({
  create: { width: 120, height: 120, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },
})
  .composite([{
    input: Buffer.from('<svg width="120" height="120"><circle cx="60" cy="60" r="55" fill="#e63946"/></svg>'),
  }])
  .png()
  .toBuffer();

await sharp('photo.jpg')
  .composite([
    { input: label, gravity: 'southeast' },  // bottom-right corner
    { input: logo, top: 20, left: 20 },      // exact position
  ])
  .toFile('watermarked.jpg');

// text rendered by sharp itself (uses Pango, supports simple markup)
const info = await sharp({
  text: {
    text: '<span foreground="#1e3c72"><b>Hello</b>, images!</span>',
    font: 'sans 48',
    rgba: true,
    dpi: 72,
  },
})
  .png()
  .toFile('text.png');
console.log('text image:', `${info.width}x${info.height}`, 'channels', info.channels);
text image: 380x47 channels 4

The result has a red circle in the top-left corner and a translucent "© Example Photos" box in the bottom-right corner. An overlay must not be larger than the base image, otherwise composite() throws.

Text is rendered with whatever fonts are installed on the machine (found via fontconfig). A generic family like sans-serif can map to different fonts on Windows, macOS and a slim Docker image, and a missing font can turn text into boxes. For predictable output, install the font you need on the server and name it explicitly.

Working with raw pixels

raw() output gives you the decoded, uncompressed pixel bytes: for an RGB image, three bytes per pixel, row after row. The raw input option goes the other way, turning a pixel buffer back into an image:

import sharp from 'sharp';

// decode to raw, uncompressed RGB bytes
const { data, info } = await sharp('photo.jpg')
  .resize({ width: 300 })
  .raw()
  .toBuffer({ resolveWithObject: true });
console.log(info);
console.log('bytes:', data.length, '=', info.width, '*', info.height, '*', info.channels);

// read one pixel: (x, y) -> offset
function pixel(x, y) {
  const i = (y * info.width + x) * info.channels;
  return [data[i], data[i + 1], data[i + 2]];
}
console.log('sun pixel   (225, 50):', pixel(225, 50));
console.log('sky pixel   (10, 10): ', pixel(10, 10));

// manipulate pixels: swap red and blue channels
for (let i = 0; i < data.length; i += info.channels) {
  [data[i], data[i + 2]] = [data[i + 2], data[i]];
}

// encode raw bytes back into a PNG; sharp needs to be told the layout
await sharp(data, {
  raw: { width: info.width, height: info.height, channels: info.channels },
})
  .png()
  .toFile('swapped.png');

// build an image from scratch, pixel by pixel: a 256x256 gradient
const w = 256, h = 256;
const pixels = Buffer.alloc(w * h * 3);
for (let y = 0; y < h; y++) {
  for (let x = 0; x < w; x++) {
    const i = (y * w + x) * 3;
    pixels[i] = x;       // red grows to the right
    pixels[i + 1] = y;   // green grows downwards
    pixels[i + 2] = 128;
  }
}
const g = await sharp(pixels, { raw: { width: w, height: h, channels: 3 } })
  .png()
  .toFile('gradient.png');
console.log('gradient.png', g.size, 'bytes');
{
  format: 'raw',
  width: 300,
  height: 200,
  channels: 3,
  depth: 'uchar',
  premultiplied: false,
  hasAlpha: false,
  size: 180000
}
bytes: 180000 = 300 * 200 * 3
sun pixel   (225, 50): [ 254, 215, 0 ]
sky pixel   (10, 10):  [ 31, 60, 116 ]
gradient.png 139594 bytes

The pixel at (x, y) starts at byte (y * width + x) * channels. Images with transparency have 4 channels (RGBA); call ensureAlpha() or removeAlpha() first if your code assumes a fixed number. Looping over pixels in JavaScript is fine for small images and analysis; for heavy work prefer sharp's built-in operations, which run in C on multiple threads.

Detecting the image type from its bytes

Don't trust a file's extension or the Content-Type of an upload. Image formats begin with a fixed signature ("magic bytes"), so the real type can be checked by reading a few bytes, no library needed:

import { open } from 'node:fs/promises';

const signatures = [
  { type: 'image/png', bytes: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] },
  { type: 'image/jpeg', bytes: [0xff, 0xd8, 0xff] },
  { type: 'image/gif', bytes: [0x47, 0x49, 0x46, 0x38] },            // "GIF8"
  { type: 'image/webp', bytes: [0x52, 0x49, 0x46, 0x46], extra: [8, 'WEBP'] },
];

async function detectImageType(path) {
  const fh = await open(path, 'r');
  try {
    const head = Buffer.alloc(16);
    await fh.read(head, 0, head.length, 0);
    for (const sig of signatures) {
      const matches = sig.bytes.every((b, i) => head[i] === b);
      if (!matches) continue;
      if (sig.extra) {
        const [offset, text] = sig.extra;
        if (head.toString('ascii', offset, offset + text.length) !== text) continue;
      }
      return sig.type;
    }
    return null;
  } finally {
    await fh.close();
  }
}

// only PNG stores width and height at a fixed place: bytes 16..23 of the IHDR chunk
async function pngSize(path) {
  const fh = await open(path, 'r');
  try {
    const buf = Buffer.alloc(24);
    await fh.read(buf, 0, 24, 0);
    return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
  } finally {
    await fh.close();
  }
}

for (const f of ['photo.jpg', 'orange.png', 'orange.gif', 'photo.webp', '09-detect.js']) {
  console.log(f.padEnd(13), await detectImageType(f));
}
console.log('orange.png size:', await pngSize('orange.png'));
photo.jpg     image/jpeg
orange.png    image/png
orange.gif    image/gif
photo.webp    image/webp
09-detect.js  null
orange.png size: { width: 400, height: 300 }

When sharp is installed, (await sharp(buf).metadata()).format does the same job for every format it supports, and also tells you the dimensions.

Generating thumbnails in bulk

Each sharp call already uses several threads inside libvips, so starting hundreds of conversions at once with Promise.all() doesn't make them faster, it only multiplies memory use. Process a few at a time:

import { mkdir, readdir } from 'node:fs/promises';
import path from 'node:path';
import sharp from 'sharp';

const srcDir = 'photos';
const outDir = 'thumbs';

// create 12 test photos with different colors and sizes
await mkdir(srcDir, { recursive: true });
for (let i = 0; i < 12; i++) {
  await sharp({
    create: { width: 2000 + i * 100, height: 1500, channels: 3, background: { r: i * 20, g: 100, b: 150 } },
  }).jpeg().toFile(path.join(srcDir, `img${String(i).padStart(2, '0')}.jpg`));
}

console.log('libvips threads per image:', sharp.concurrency());

await mkdir(outDir, { recursive: true });
const files = (await readdir(srcDir)).filter((f) => /\.(jpe?g|png|webp)$/i.test(f));

async function makeThumb(file) {
  const out = path.join(outDir, path.parse(file).name + '.webp');
  const info = await sharp(path.join(srcDir, file))
    .autoOrient()
    .resize(256, 256, { fit: 'cover', position: 'attention' })
    .webp({ quality: 75 })
    .toFile(out);
  return `${file} -> ${path.basename(out)} (${info.size} bytes)`;
}

// process at most 4 images at a time to bound memory use
async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next++;
      results[i] = await fn(items[i]);
    }
  }
  await Promise.all(Array.from({ length: limit }, worker));
  return results;
}

const start = performance.now();
const results = await mapLimit(files, 4, makeThumb);
console.log(results.slice(0, 3).join('\n'));
console.log(`... ${results.length} thumbnails in ${(performance.now() - start).toFixed(0)} ms`);
libvips threads per image: 24
img00.jpg -> img00.webp (198 bytes)
img01.jpg -> img01.webp (200 bytes)
img02.jpg -> img02.webp (198 bytes)
... 12 thumbnails in 256 ms

sharp.concurrency() defaults to the number of CPU cores. Pipelines also run on libuv's thread pool, which has 4 threads unless you set the UV_THREADPOOL_SIZE environment variable, so a limit of 2-4 concurrent images is usually enough to keep every core busy. position: 'attention' crops each square thumbnail around the most salient part of the image instead of its center.

Streaming

A pipeline created with sharp() and no input is a duplex stream. Encoded bytes go in and encoded bytes come out, which fits stream pipelines for files, HTTP bodies and cloud storage:

import { createReadStream, createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import sharp from 'sharp';

// a sharp instance is a Duplex stream: write encoded bytes in, read encoded bytes out
const resizer = sharp()
  .resize({ width: 320 })
  .webp()
  .on('info', (info) => console.log('output:', info.format, `${info.width}x${info.height}`));

await pipeline(
  createReadStream('photo.jpg'),
  resizer,
  createWriteStream('photo-320.webp'),
);
console.log('done');
output: webp 320x213
done

Most formats need the whole image before the first output byte can be produced, so streaming saves you from holding the input and output in JavaScript buffers, but not from decoding the whole image.

Resizing images on demand in a web server

A common pattern is an endpoint that returns a resized version of a stored image. The important parts are validating the parameters (otherwise anyone can make your server generate images at thousands of arbitrary sizes) and not letting the file name escape the image directory. This example serves the photos created by the bulk thumbnail script:

import path from 'node:path';
import express from 'express';
import sharp from 'sharp';

const IMAGE_DIR = path.resolve('photos');
const FORMATS = { webp: 'image/webp', avif: 'image/avif', jpeg: 'image/jpeg', png: 'image/png' };
const WIDTHS = new Set([128, 256, 512, 1024]);

const app = express();

// GET /img/img03.jpg?w=256&format=webp
app.get('/img/:name', async (req, res) => {
  const width = Number(req.query.w ?? 512);
  const format = String(req.query.format ?? 'webp');
  if (!WIDTHS.has(width) || !(format in FORMATS)) {
    return res.status(400).send('bad w or format');
  }

  // basename() strips any "../" so requests can't escape IMAGE_DIR
  const file = path.join(IMAGE_DIR, path.basename(req.params.name));

  try {
    const buf = await sharp(file)
      .autoOrient()
      .resize({ width, withoutEnlargement: true })
      .toFormat(format, { quality: 75 })
      .toBuffer();
    res.type(FORMATS[format]);
    res.set('Cache-Control', 'public, max-age=86400');
    res.send(buf);
  } catch (err) {
    res.status(404).send('not found');
  }
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  for (const q of ['img03.jpg?w=256', 'img03.jpg?w=128&format=avif', 'img03.jpg?w=300', 'nope.jpg']) {
    const r = await fetch(`${base}/img/${q}`);
    const body = Buffer.from(await r.arrayBuffer());
    console.log(q.padEnd(28), r.status, r.headers.get('content-type'), body.length, 'bytes');
  }
  server.close();
});
img03.jpg?w=256              200 image/webp 178 bytes
img03.jpg?w=128&format=avif  200 image/avif 293 bytes
img03.jpg?w=300              400 text/html; charset=utf-8 15 bytes
nope.jpg                     404 text/html; charset=utf-8 9 bytes

In production, put a CDN or a disk cache in front of such an endpoint so each size is generated only once, and choose the format from the request's Accept header (image/avif, image/webp) rather than from a query parameter. For accepting images from users, see File upload and Single File Upload using multer; multer's memory storage gives you a Buffer that you can pass straight to sharp().

Handling untrusted images safely

Images uploaded by users can be broken, huge or deliberately malicious. A small PNG can decode to gigapixels (a "decompression bomb"). sharp has options to guard against this:

import { readFile } from 'node:fs/promises';
import sharp from 'sharp';

const upload = await readFile('photos/img00.jpg'); // 2000x1500

// 1. reject images with too many pixels before decoding them
try {
  await sharp(upload, { limitInputPixels: 1_000_000 }).resize(100).toBuffer();
} catch (err) {
  console.log('too big:', err.message);
}

// 2. garbage that isn't an image
try {
  await sharp(Buffer.from('definitely not an image')).metadata();
} catch (err) {
  console.log('garbage:', err.message);
}

// 3. a truncated upload: rejected by default, failOn: 'none' decodes what it can
const truncated = upload.subarray(0, upload.length / 2);
try {
  await sharp(truncated).resize(100).toBuffer();
} catch (err) {
  console.log('truncated, default:', err.message);
}
const partial = await sharp(truncated, { failOn: 'none' }).resize(100).toBuffer();
console.log('truncated, lenient:', partial.length, 'bytes produced');

// 4. check metadata cheaply (only the header is parsed) before doing real work
const { width, height, format } = await sharp(upload).metadata();
if (!['jpeg', 'png', 'webp'].includes(format) || width * height > 50_000_000) {
  throw new Error('unsupported upload');
}
console.log('accepted', format, `${width}x${height}`);
too big: Input image exceeds pixel limit
garbage: Input buffer contains unsupported image format
truncated, default: VipsJpeg: premature end of JPEG image
truncated, lenient: 513 bytes produced
accepted jpeg 2000x1500

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents