gm vs canvas vs image-size vs jimp vs sharp
Server-Side Image Processing in Node.js
gmcanvasimage-sizejimpsharpSimilar 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
gm742,5286,981121 kB368a year agoMIT
canvas010,677403 kB4683 months agoMIT
image-size02,226378 kB45a year agoMIT
jimp014,6263.31 MB1793 months agoMIT
sharp032,396950 kB1098 days 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: gm vs canvas vs image-size vs jimp vs sharp

  • 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.

  • 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.

  • 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.

  • 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.

  • 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 gm

gm Build Status NPM Version

GraphicsMagick and ImageMagick for node

Bug Reports

When reporting bugs please include the version of graphicsmagick/imagemagick you're using (gm -version/convert -version) as well as the version of this module and copies of any images you're having problems with.

Getting started

First download and install GraphicsMagick or ImageMagick. In Mac OS X, you can simply use Homebrew and do:

brew install imagemagick
brew install graphicsmagick

then either use npm:

npm install gm

or clone the repo:

git clone git://github.com/aheckmann/gm.git

Use ImageMagick instead of gm

Subclass gm to enable ImageMagick 7+

const fs = require('fs')
const gm = require('gm').subClass({ imageMagick: '7+' });

Or, to enable ImageMagick legacy mode (for ImageMagick version < 7)

const fs = require('fs')
const gm = require('gm').subClass({ imageMagick: true });

Specify the executable path

Optionally specify the path to the executable.

const fs = require('fs')
const gm = require('gm').subClass({
  appPath: String.raw`C:\Program Files\ImageMagick-7.1.0-Q16-HDRI\magick.exe`
});

Basic Usage

var fs = require('fs')
  , gm = require('gm');

// resize and remove EXIF profile data
gm('/path/to/my/img.jpg')
.resize(240, 240)
.noProfile()
.write('/path/to/resize.png', function (err) {
  if (!err) console.log('done');
});

// some files would not be resized appropriately
// http://stackoverflow.com/questions/5870466/imagemagick-incorrect-dimensions
// you have two options:
// use the '!' flag to ignore aspect ratio
gm('/path/to/my/img.jpg')
.resize(240, 240, '!')
.write('/path/to/resize.png', function (err) {
  if (!err) console.log('done');
});

// use the .resizeExact with only width and/or height arguments
gm('/path/to/my/img.jpg')
.resizeExact(240, 240)
.write('/path/to/resize.png', function (err) {
  if (!err) console.log('done');
});

// obtain the size of an image
gm('/path/to/my/img.jpg')
.size(function (err, size) {
  if (!err)
    console.log(size.width > size.height ? 'wider' : 'taller than you');
});

// output all available image properties
gm('/path/to/img.png')
.identify(function (err, data) {
  if (!err) console.log(data)
});

// pull out the first frame of an animated gif and save as png
gm('/path/to/animated.gif[0]')
.write('/path/to/firstframe.png', function (err) {
  if (err) console.log('aaw, shucks');
});

// auto-orient an image
gm('/path/to/img.jpg')
.autoOrient()
.write('/path/to/oriented.jpg', function (err) {
  if (err) ...
})

// crazytown
gm('/path/to/my/img.jpg')
.flip()
.magnify()
.rotate('green', 45)
.blur(7, 3)
.crop(300, 300, 150, 130)
.edge(3)
.write('/path/to/crazy.jpg', function (err) {
  if (!err) console.log('crazytown has arrived');
})

// annotate an image
gm('/path/to/my/img.jpg')
.stroke("#ffffff")
.drawCircle(10, 10, 20, 10)
.font("Helvetica.ttf", 12)
.drawText(30, 20, "GMagick!")
.write("/path/to/drawing.png", function (err) {
  if (!err) console.log('done');
});

// creating an image
gm(200, 400, "#ddff99f3")
.drawText(10, 50, "from scratch")
.write("/path/to/brandNewImg.jpg", function (err) {
  // ...
});

Streams

// passing a stream
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream, 'img.jpg')
.write('/path/to/reformat.png', function (err) {
  if (!err) console.log('done');
});


// passing a downloadable image by url

var request = require('request');
var url = "www.abc.com/pic.jpg"

gm(request(url))
.write('/path/to/reformat.png', function (err) {
  if (!err) console.log('done');
});


// can also stream output to a ReadableStream
// (can be piped to a local file or remote server)
gm('/path/to/my/img.jpg')
.resize('200', '200')
.stream(function (err, stdout, stderr) {
  var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
  stdout.pipe(writeStream);
});

// without a callback, .stream() returns a stream
// this is just a convenience wrapper for above.
var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
gm('/path/to/my/img.jpg')
.resize('200', '200')
.stream()
.pipe(writeStream);

// pass a format or filename to stream() and
// gm will provide image data in that format
gm('/path/to/my/img.jpg')
.stream('png', function (err, stdout, stderr) {
  var writeStream = fs.createWriteStream('/path/to/my/reformatted.png');
  stdout.pipe(writeStream);
});

// or without the callback
var writeStream = fs.createWriteStream('/path/to/my/reformatted.png');
gm('/path/to/my/img.jpg')
.stream('png')
.pipe(writeStream);

// combine the two for true streaming image processing
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream)
.resize('200', '200')
.stream(function (err, stdout, stderr) {
  var writeStream = fs.createWriteStream('/path/to/my/resized.jpg');
  stdout.pipe(writeStream);
});

// GOTCHA:
// when working with input streams and any 'identify'
// operation (size, format, etc), you must pass "{bufferStream: true}" if
// you also need to convert (write() or stream()) the image afterwards
// NOTE: this buffers the readStream in memory!
var readStream = fs.createReadStream('/path/to/my/img.jpg');
gm(readStream)
.size({bufferStream: true}, function(err, size) {
  this.resize(size.width / 2, size.height / 2)
  this.write('/path/to/resized.jpg', function (err) {
    if (!err) console.log('done');
  });
});

Buffers

// A buffer can be passed instead of a filepath as well
var buf = require('fs').readFileSync('/path/to/image.jpg');

gm(buf, 'image.jpg')
.noise('laplacian')
.write('/path/to/out.jpg', function (err) {
  if (err) return handle(err);
  console.log('Created an image from a Buffer!');
});

/*
A buffer can also be returned instead of a stream
The first argument to toBuffer is optional, it specifies the image format
*/
gm('img.jpg')
.resize(100, 100)
.toBuffer('PNG',function (err, buffer) {
  if (err) return handle(err);
  console.log('done!');
})

Custom Arguments

If gm does not supply you with a method you need or does not work as you'd like, you can simply use gm().in() or gm().out() to set your own arguments.

  • gm().command() - Custom command such as identify or convert
  • gm().in() - Custom input arguments
  • gm().out() - Custom output arguments

The command will be formatted in the following order:

  1. command - ie convert
  2. in - the input arguments
  3. source - stdin or an image file
  4. out - the output arguments
  5. output - stdout or the image file to write to

For example, suppose you want the following command:

gm "convert" "label:Offline" "PNG:-"

However, using gm().label() may not work as intended for you:

gm()
.label('Offline')
.stream();

would yield:

gm "convert" "-label" "\"Offline\"" "PNG:-"

Instead, you can use gm().out():

gm()
.out('label:Offline')
.stream();

which correctly yields:

gm "convert" "label:Offline" "PNG:-"

Custom Identify Format String

When identifying an image, you may want to use a custom formatting string instead of using -verbose, which is quite slow. You can use your own formatting string when using gm().identify(format, callback). For example,

gm('img.png').format(function (err, format) {

})

// is equivalent to

gm('img.png').identify('%m', function (err, format) {

})

since %m is the format option for getting the image file format.

Platform differences

Please document and refer to any platform or ImageMagick/GraphicsMagick issues/differences here.

Examples:

Check out the examples directory to play around. Also take a look at the extending gm page to see how to customize gm to your own needs.

Constructor:

There are a few ways you can use the gm image constructor.

    1. gm(path) When you pass a string as the first argument it is interpreted as the path to an image you intend to manipulate.
    1. gm(stream || buffer, [filename]) You may also pass a ReadableStream or Buffer as the first argument, with an optional file name for format inference.
    1. gm(width, height, [color]) When you pass two integer arguments, gm will create a new image on the fly with the provided dimensions and an optional background color. And you can still chain just like you do with pre-existing images too. See here for an example.

The links below refer to an older version of gm but everything should still work, if anyone feels like updating them please make a PR

Methods

compare

Graphicsmagicks compare command is exposed through gm.compare(). This allows us to determine if two images can be considered "equal".

Currently gm.compare only accepts file paths.

gm.compare(path1, path2 [, options], callback)
gm.compare('/path/to/image1.jpg', '/path/to/another.png', function (err, isEqual, equality, raw, path1, path2) {
  if (err) return handle(err);

  // if the images were considered equal, `isEqual` will be true, otherwise, false.
  console.log('The images were equal: %s', isEqual);

  // to see the total equality returned by graphicsmagick we can inspect the `equality` argument.
  console.log('Actual equality: %d', equality);

  // inspect the raw output
  console.log(raw);

  // print file paths
  console.log(path1, path2);
})

You may wish to pass a custom tolerance threshold to increase or decrease the default level of 0.4.

gm.compare('/path/to/image1.jpg', '/path/to/another.png', 1.2, function (err, isEqual) {
  ...
})

To output a diff image, pass a configuration object to define the diff options and tolerance.

var options = {
  file: '/path/to/diff.png',
  highlightColor: 'yellow',
  tolerance: 0.02
}
gm.compare('/path/to/image1.jpg', '/path/to/another.png', options, function (err, isEqual, equality, raw) {
  ...
})

composite

GraphicsMagick supports compositing one image on top of another. This is exposed through gm.composite(). Its first argument is an image path with the changes to the base image, and an optional mask image.

Currently, gm.composite() only accepts file paths.

gm.composite(other [, mask])
gm('/path/to/image.jpg')
.composite('/path/to/second_image.jpg')
.geometry('+100+150')
.write('/path/to/composite.png', function(err) {
    if(!err) console.log("Written composite image.");
});

montage

GraphicsMagick supports montage for combining images side by side. This is exposed through gm.montage(). Its only argument is an image path with the changes to the base image.

Currently, gm.montage() only accepts file paths.

gm.montage(other)
gm('/path/to/image.jpg')
.montage('/path/to/second_image.jpg')
.geometry('+100+150')
.write('/path/to/montage.png', function(err) {
    if(!err) console.log("Written montage image.");
});

Contributors

https://github.com/aheckmann/gm/contributors

Inspiration

http://github.com/quiiver/magickal-node

Plugins

https://github.com/aheckmann/gm/wiki

Tests

npm test

To run a single test:

npm test -- alpha.js

License

(The MIT License)

Copyright (c) 2010 Aaron Heckmann

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.