image-size vs canvas vs jimp vs gm vs sharp
Server-Side Image Processing in Node.js
image-sizecanvasjimpgmsharpSimilar Packages:

Server-Side Image Processing in Node.js

sharp, jimp, canvas, gm, and image-size are Node.js libraries used for handling image files, but they serve different architectural needs. sharp is a high-performance module built on libvips, optimized for resizing and format conversion in production environments. jimp is a pure JavaScript library with zero system dependencies, making it portable but slower. canvas (node-canvas) implements the HTML5 Canvas API for Node, ideal for dynamic image generation and text rendering. gm wraps GraphicsMagick or ImageMagick, offering powerful features but requiring external system binaries. image-size is a lightweight utility dedicated solely to reading image dimensions without processing the file content.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
image-size18,705,672-95.5 kB-a month agoMIT
canvas5,180,27310,699403 kB4247 months agoMIT
jimp2,038,56214,6723.31 MB1897 months agoMIT
gm430,5596,974121 kB3662 years agoMIT
sharp032,795962 kB122a month agoApache-2.0

Server-Side Image Processing: Sharp, Jimp, Canvas, GM, and Image-Size

When building Node.js applications that handle images, choosing the right library impacts performance, deployment complexity, and feature availability. sharp, jimp, canvas, gm, and image-size each take a different approach to solving image problems. Let's compare how they handle common engineering tasks.

🏗️ Architecture: Native Bindings vs Pure JavaScript

The core difference lies in how these packages process pixels. This dictates speed and installation requirements.

sharp uses native C++ bindings to libvips.

  • Extremely fast and memory efficient.
  • Requires downloading prebuilt binaries during install.
// sharp: Native binding usage
const sharp = require('sharp');
// Installs with prebuilt libvips binaries for most OS

jimp is written entirely in JavaScript.

  • Slower on large images but runs everywhere Node runs.
  • No compilation or system libraries needed.
// jimp: Pure JavaScript
const Jimp = require('jimp');
// Zero system dependencies, pure JS implementation

canvas wraps the Cairo graphics library.

  • Implements the browser Canvas API for Node.
  • Requires system dependencies like Cairo and Pango on Linux.
// canvas: Cairo binding
const { createCanvas } = require('canvas');
// Needs system libs: libcairo2-dev, libpango1.0-dev, etc.

gm spawns child processes for GraphicsMagick/ImageMagick.

  • Relies on external binaries installed on the server OS.
  • Can be brittle if system tools are missing or versioned differently.
// gm: System binary wrapper
const gm = require('gm');
// Requires 'graphicsmagick' or 'imagemagick' installed on OS

image-size reads file headers directly.

  • Does not process pixels, just reads metadata bytes.
  • Minimal footprint, no heavy dependencies.
// image-size: Header reader
const sizeOf = require('image-size');
// Reads bytes to determine dimensions, no image decoding

🖼️ Resizing Images

Resizing is the most common operation. The API style varies from promises to callbacks.

sharp uses a chainable promise-based API.

  • Streaming support available for large files.
  • High-quality resampling algorithms built-in.
// sharp: Resize with promises
await sharp('input.jpg')
  .resize(800, 600)
  .toFile('output.jpg');

jimp uses a promise-based chain on the image object.

  • Simple API but blocks the event loop on large images.
// jimp: Resize with chains
await Jimp.read('input.jpg')
  .then(img => img.resize(800, 600))
  .then(img => img.write('output.jpg'));

canvas requires manual drawing onto a new surface.

  • More verbose but allows full control over rendering context.
// canvas: Manual draw and resize
const { createCanvas, loadImage } = require('canvas');
const img = await loadImage('input.jpg');
const canvas = createCanvas(800, 600);
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, 800, 600);
// Write buffer to file using fs

gm uses a callback-based or promise-wrapped API.

  • Powerful options but older coding style.
// gm: Resize with callbacks
const gm = require('gm').subClass({ imageMagick: true });
gm('input.jpg').resize(800, 600).write('output.jpg', (err) => {
  if (err) console.error(err);
});

image-size does not support resizing.

  • Attempting to resize will fail as it is metadata-only.
// image-size: Resizing NOT supported
// This package only reads dimensions, cannot modify images
const dimensions = sizeOf('input.jpg');
// Cannot resize, use sharp or jimp for modification

📏 Reading Metadata

Knowing dimensions before processing is vital for validation.

sharp provides metadata via a dedicated method.

  • Returns format, size, and color space info.
// sharp: Get metadata
const metadata = await sharp('input.jpg').metadata();
console.log(metadata.width, metadata.height);

jimp exposes dimensions on the loaded object.

  • You must load the file first to access properties.
// jimp: Get dimensions
const img = await Jimp.read('input.jpg');
console.log(img.bitmap.width, img.bitmap.height);

canvas exposes dimensions on the loaded image object.

  • Similar to browser Image object behavior.
// canvas: Image properties
const img = await loadImage('input.jpg');
console.log(img.width, img.height);

gm includes size in the identify command.

  • Can be slow as it may invoke external process.
// gm: Identify size
gm('input.jpg').identify((err, features) => {
  console.log(features.size);
});

image-size is specialized for this exact task.

  • Fastest option for just width and height.
// image-size: Dedicated dimension reader
const dimensions = sizeOf('input.jpg');
console.log(dimensions.width, dimensions.height);

🎨 Drawing and Text Rendering

Some tasks require creating images from scratch or overlaying text.

sharp has limited drawing capabilities.

  • Can overlay images but text rendering requires external assets.
// sharp: Composite overlay
await sharp('background.jpg')
  .composite([{ input: 'logo.png', top: 10, left: 10 }])
  .toFile('output.jpg');

jimp supports basic text and drawing.

  • Built-in fonts but limited styling options.
// jimp: Print text
const img = await Jimp.read('background.jpg');
const font = await Jimp.loadFont(Jimp.FONT_SANS_16_WHITE);
img.print(font, 10, 10, 'Hello World');
img.write('output.jpg');

canvas excels at text and vector drawing.

  • Full support for fonts, paths, and complex compositing.
// canvas: Draw text and shapes
const ctx = canvas.getContext('2d');
ctx.font = '20px Arial';
ctx.fillText('Hello World', 10, 50);
ctx.fillRect(0, 0, 100, 100);

gm supports text via ImageMagick commands.

  • Complex syntax for styling and positioning.
// gm: Draw text
const image = gm('background.jpg');
image.draw('text 10,50 "Hello World"').write('output.jpg', cb);

image-size cannot draw or create images.

  • Read-only utility.
// image-size: No drawing capabilities
// Cannot create or modify image content

🚀 Deployment and Dependencies

How the package installs affects your CI/CD pipeline and container size.

sharp downloads binaries automatically.

  • Keeps Docker images small if using distroless or alpine correctly.
  • May need libc6-compat on Alpine Linux.
# sharp: Docker example
FROM node:18-alpine
RUN apk add --no-cache libc6-compat
# npm install sharp downloads binaries

jimp installs like any JS package.

  • No Docker special handling required.
  • Larger node_modules due to pure JS code.
# jimp: Docker example
FROM node:18-alpine
# No system deps needed
COPY package*.json .
RUN npm install

canvas requires build tools and system libs.

  • Heavy Docker image if not multi-stage built.
# canvas: Docker example
FROM node:18-alpine
RUN apk add --no-cache build-base glib-dev libpng-dev jpeg-dev
# Compilation happens during npm install

gm requires the binary installed on the OS.

  • You must manage ImageMagick version separately.
# gm: Docker example
FROM node:18-alpine
RUN apk add --no-cache graphicsmagick
# Ensure binary matches expected version

image-size has no special requirements.

  • Lightweight and safe for any environment.
# image-size: Docker example
FROM node:18-alpine
# Standard node image works fine

🌱 Similarities: Shared Ground

Despite their differences, these libraries share some common patterns and goals.

1. 📂 File Input and Output

  • All processing libraries (sharp, jimp, canvas, gm) accept file paths or buffers.
  • All support writing to disk or returning a buffer for cloud storage.
// Shared pattern: Buffer handling
// sharp
const buffer = await sharp(input).toBuffer();
// jimp
const buffer = await img.getBufferAsync(Jimp.MIME_JPEG);

2. 🔄 Async Operations

  • All libraries operate asynchronously to avoid blocking the Node.js event loop.
  • sharp and jimp use Promises natively.
  • gm traditionally uses callbacks but supports promises via wrappers.
// Shared pattern: Async/Await
await processImage('input.jpg'); // Works for sharp, jimp, canvas

3. 🛡️ Error Handling

  • All libraries throw errors or return error objects for invalid files.
  • Essential for validating user uploads before processing.
// Shared pattern: Try/Catch
try {
  await sharp('invalid.jpg').metadata();
} catch (e) {
  console.error('Invalid image file');
}

📊 Summary: Capabilities

Featuresharpjimpcanvasgmimage-size
Primary UseProcessingProcessingDrawingProcessingMetadata
LanguageC++ / JSPure JSC++ / JSSystem BinPure JS
Resize✅ Fast✅ Slow✅ Manual✅ Fast❌ No
Text/Draw⚠️ Limited✅ Basic✅ Advanced✅ Advanced❌ No
DependenciesBinariesNoneSystem LibsSystem BinNone
API StylePromisesPromisesPromisesCallbacksSync/Async

🆚 Summary: Performance and Effort

PackageSpeedInstall EffortMemory UsageBest For
sharp⚡ Very HighLow (Auto-bin)LowProduction APIs
jimp🐢 LowNoneHighSimple Scripts
canvas⚡ HighHigh (Build)MediumDynamic Graphics
gm⚡ HighHigh (System)MediumLegacy Systems
image-size⚡ InstantNoneLowValidation

💡 The Big Picture

sharp is the industry standard for modern Node.js image processing. It balances speed and ease of use better than any other option. Use it for resizing user uploads, generating thumbnails, or converting formats in production.

jimp is the fallback for when you cannot install native modules. It works in browsers and restricted server environments but will struggle with large files or high concurrency.

canvas is the choice for creative tasks. If you need to draw charts, add dynamic text, or composite layers like a design tool, this provides the most control.

gm is a legacy tool. While powerful, the requirement to manage system binaries and its callback-heavy API makes it less attractive for new greenfield projects.

image-size is a utility, not a processor. Keep it in your toolkit for quick validation checks before handing files off to sharp or jimp.

Final Thought: For most backend image tasks, start with sharp. It solves 90% of problems with the least friction. Reach for canvas only when you need to draw, and jimp only when you must avoid native dependencies.

How to Choose: image-size vs canvas vs jimp vs gm vs sharp

  • image-size:

    Choose image-size when you strictly need to read image width and height without modifying the file. It is perfect for validation steps before upload or calculating layout dimensions without the overhead of a full processing library.

  • canvas:

    Choose canvas when you need to draw images from scratch, render text onto images, or manipulate pixels using the familiar HTML5 Canvas API. It is ideal for generating charts, memes, or dynamic social media cards server-side.

  • jimp:

    Choose jimp if you need a pure JavaScript solution that runs anywhere without compiling native modules or installing system libraries. It is suitable for low-volume tasks, prototyping, or environments where installing native dependencies is impossible.

  • gm:

    Choose gm only if you are maintaining a legacy system that already depends on GraphicsMagick or ImageMagick. For new projects, it is generally recommended to avoid this package in favor of sharp due to better performance and easier deployment.

  • sharp:

    Choose sharp for production-grade image processing where performance and memory efficiency are critical. It is the best fit for resizing, cropping, and converting formats in high-traffic APIs or serverless functions due to its native bindings and prebuilt binaries.

README for image-size

image-size

Build Status Package Version Downloads

Fast, lightweight NodeJS package to get dimensions of any image file or buffer.

Key Features

  • Zero dependencies
  • Supports all major image formats
  • Works with both files and buffers
  • Minimal memory footprint - reads only image headers
  • ESM and CommonJS support
  • TypeScript types included

Supported formats

  • BMP
  • CUR
  • DDS
  • GIF
  • HEIC (HEIF, AVCI, AVIF)
  • ICNS
  • ICO
  • J2C
  • JPEG-2000 (JP2)
  • JPEG
  • JPEG-XL
  • KTX (1 and 2)
  • PNG
  • PNM (PAM, PBM, PFM, PGM, PPM)
  • PSD
  • SVG
  • TGA
  • TIFF
  • WebP

Installation

npm install image-size
# or
yarn add image-size
# or
pnpm add image-size

Usage

Passing in a Buffer/Uint8Array

Best for streams, network requests, or when you already have the image data in memory.

import { imageSize } from 'image-size'
// or
const { imageSize } = require('image-size')

const dimensions = imageSize(buffer)
console.log(dimensions.width, dimensions.height)

Reading from a file

Best for local files. Returns a promise.

import { imageSizeFromFile } from 'image-size/fromFile'
// or
const { imageSizeFromFile } = require('image-size/fromFile')

const dimensions = await imageSizeFromFile('photos/image.jpg')
console.log(dimensions.width, dimensions.height)

Note: Reading from files has a default concurrency limit of 100 To change this limit, you can call the setConcurrency function like this:

import { setConcurrency } from 'image-size/fromFile'
// or
const { setConcurrency } = require('image-size/fromFile')
setConcurrency(123456)

Reading from a file Syncronously (not recommended) ⚠️

v1.x of this library had a sync API, that internally used sync file reads.

This isn't recommended because this blocks the node.js main thread, which reduces the performance, and prevents this library from being used concurrently.

However if you still need to use this package syncronously, you can read the file syncronously into a buffer, and then pass the buffer to this library.

import { readFileSync } from 'node:fs'
import { imageSize } from 'image-size'

const buffer = readFileSync('photos/image.jpg')
const dimensions = imageSize(buffer)
console.log(dimensions.width, dimensions.height)

3. Command Line

Useful for quick checks.

npx image-size image1.jpg image2.png

Multi-size

If the target file/buffer is an HEIF, an ICO, or a CUR file, the width and height will be the ones of the largest image in the set.

An additional images array is available and returns the dimensions of all the available images

import { imageSizeFromFile } from 'image-size/fromFile'
// or
const { imageSizeFromFile } = require('image-size/fromFile')

const { images } = await imageSizeFromFile('images/multi-size.ico')
for (const dimensions of images) {
  console.log(dimensions.width, dimensions.height)
}

Using a URL

import url from 'node:url'
import http from 'node:http'
import { imageSize } from 'image-size'

const imgUrl = 'http://my-amazing-website.com/image.jpeg'
const options = url.parse(imgUrl)

http.get(options, function (response) {
  const chunks = []
  response
    .on('data', function (chunk) {
      chunks.push(chunk)
    })
    .on('end', function () {
      const buffer = Buffer.concat(chunks)
      console.log(imageSize(buffer))
    })
})

Disabling certain image types

import { disableTypes } from 'image-size'
// or
const { disableTypes } = require('image-size')

disableTypes(['tiff', 'ico'])

JPEG image orientation

If the orientation is present in the JPEG EXIF metadata, it will be returned by the function. The orientation value is a number between 1 and 8 representing a type of orientation.

import { imageSizeFromFile } from 'image-size/fromFile'
// or
const { imageSizeFromFile } = require('image-size/fromFile')

const { width, height, orientation } = await imageSizeFromFile('images/photo.jpeg')
console.log(width, height, orientation)

Limitations

  1. Partial File Reading

    • Only reads image headers, not full files
    • Some corrupted images might still report dimensions
  2. SVG Limitations

    • Only supports pixel dimensions and viewBox
    • Percentage values not supported
  3. File Access

    • Reading from files has a default concurrency limit of 100
    • Can be adjusted using setConcurrency()
  4. Buffer Requirements

    • Some formats (like TIFF) require the full header in buffer
    • Streaming partial buffers may not work for all formats

License

MIT

Credits

not a direct port, but an attempt to have something like dabble's imagesize as a node module.

Contributors