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.
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.
The core difference lies in how these packages process pixels. This dictates speed and installation requirements.
sharp uses native C++ bindings to libvips.
// sharp: Native binding usage
const sharp = require('sharp');
// Installs with prebuilt libvips binaries for most OS
jimp is written entirely in JavaScript.
// jimp: Pure JavaScript
const Jimp = require('jimp');
// Zero system dependencies, pure JS implementation
canvas wraps the Cairo graphics library.
// canvas: Cairo binding
const { createCanvas } = require('canvas');
// Needs system libs: libcairo2-dev, libpango1.0-dev, etc.
gm spawns child processes for GraphicsMagick/ImageMagick.
// gm: System binary wrapper
const gm = require('gm');
// Requires 'graphicsmagick' or 'imagemagick' installed on OS
image-size reads file headers directly.
// image-size: Header reader
const sizeOf = require('image-size');
// Reads bytes to determine dimensions, no image decoding
Resizing is the most common operation. The API style varies from promises to callbacks.
sharp uses a chainable promise-based API.
// sharp: Resize with promises
await sharp('input.jpg')
.resize(800, 600)
.toFile('output.jpg');
jimp uses a promise-based chain on the image object.
// 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.
// 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.
// 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.
// 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
Knowing dimensions before processing is vital for validation.
sharp provides metadata via a dedicated method.
// sharp: Get metadata
const metadata = await sharp('input.jpg').metadata();
console.log(metadata.width, metadata.height);
jimp exposes dimensions on the loaded object.
// 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.
// canvas: Image properties
const img = await loadImage('input.jpg');
console.log(img.width, img.height);
gm includes size in the identify command.
// gm: Identify size
gm('input.jpg').identify((err, features) => {
console.log(features.size);
});
image-size is specialized for this exact task.
// image-size: Dedicated dimension reader
const dimensions = sizeOf('input.jpg');
console.log(dimensions.width, dimensions.height);
Some tasks require creating images from scratch or overlaying text.
sharp has limited drawing capabilities.
// sharp: Composite overlay
await sharp('background.jpg')
.composite([{ input: 'logo.png', top: 10, left: 10 }])
.toFile('output.jpg');
jimp supports basic text and drawing.
// 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.
// 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.
// 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.
// image-size: No drawing capabilities
// Cannot create or modify image content
How the package installs affects your CI/CD pipeline and container size.
sharp downloads binaries automatically.
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.
# jimp: Docker example
FROM node:18-alpine
# No system deps needed
COPY package*.json .
RUN npm install
canvas requires build tools and system libs.
# 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.
# gm: Docker example
FROM node:18-alpine
RUN apk add --no-cache graphicsmagick
# Ensure binary matches expected version
image-size has no special requirements.
# image-size: Docker example
FROM node:18-alpine
# Standard node image works fine
Despite their differences, these libraries share some common patterns and goals.
sharp, jimp, canvas, gm) accept file paths or buffers.// Shared pattern: Buffer handling
// sharp
const buffer = await sharp(input).toBuffer();
// jimp
const buffer = await img.getBufferAsync(Jimp.MIME_JPEG);
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
// Shared pattern: Try/Catch
try {
await sharp('invalid.jpg').metadata();
} catch (e) {
console.error('Invalid image file');
}
| Feature | sharp | jimp | canvas | gm | image-size |
|---|---|---|---|---|---|
| Primary Use | Processing | Processing | Drawing | Processing | Metadata |
| Language | C++ / JS | Pure JS | C++ / JS | System Bin | Pure JS |
| Resize | ✅ Fast | ✅ Slow | ✅ Manual | ✅ Fast | ❌ No |
| Text/Draw | ⚠️ Limited | ✅ Basic | ✅ Advanced | ✅ Advanced | ❌ No |
| Dependencies | Binaries | None | System Libs | System Bin | None |
| API Style | Promises | Promises | Promises | Callbacks | Sync/Async |
| Package | Speed | Install Effort | Memory Usage | Best For |
|---|---|---|---|---|
sharp | ⚡ Very High | Low (Auto-bin) | Low | Production APIs |
jimp | 🐢 Low | None | High | Simple Scripts |
canvas | ⚡ High | High (Build) | Medium | Dynamic Graphics |
gm | ⚡ High | High (System) | Medium | Legacy Systems |
image-size | ⚡ Instant | None | Low | Validation |
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.
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.
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.
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.
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.
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.
Fast, lightweight NodeJS package to get dimensions of any image file or buffer.
npm install image-size
# or
yarn add image-size
# or
pnpm add image-size
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)
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)
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)
Useful for quick checks.
npx image-size image1.jpg image2.png
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)
}
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))
})
})
import { disableTypes } from 'image-size'
// or
const { disableTypes } = require('image-size')
disableTypes(['tiff', 'ico'])
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)
Partial File Reading
SVG Limitations
File Access
setConcurrency()Buffer Requirements
MIT
not a direct port, but an attempt to have something like dabble's imagesize as a node module.