Last Updated: February 25, 2016
·
6.11K
· Ionut-Cristian Florescu

Node.js: dependency-free image processing with ImageMagick

There's more than one way to do image processing in Node.js, but here's one requiring no additional modules:

path = require 'path'
exec = require('child_process').exec
uuid = require 'node-uuid'

exports.process = (source, callback) ->
  folder = path.dirname source
  guid   = uuid.v4()

  convertCmd = """
    convert #{source} -quality 85% \\
      -resize 620x465 -gravity center -background "#666" -extent 620x465 -write #{folder}/#{guid}-large.jpg \\
      -resize 460x345                                                    -write #{folder}/#{guid}-medium.jpg \\
      -resize 140x105                                                           #{folder}/#{guid}-small.jpg
    """

  watermarkCmd = """
    composite -dissolve 75% -gravity south \\
      ./resources/watermark.png #{folder}/#{guid}-large.jpg #{folder}/#{guid}-large.jpg
    """

  await exec convertCmd,   defer err; callback err if err
  await exec watermarkCmd, defer err; callback err if err

  callback null, guid

In plain English, the method creates 3 differently sized versions of a source image and applies a watermark on the largest one, by simply executing the appropriate shell utilities coming with ImageMagick.

The snippet above is written in IcedCoffeeScript and is slightly adapted from one of my projects; node-uuid is used there to generate unique names.

You need to have ImageMagick properly installed; the easiest way on OS X is brew install imagemagick.

Works perfectly on Heroku and most likely on other PaaS providers as well.

Node.js & ImageMagick

2 Responses
Add your response

Sorry about the apparently misaligned code in the above sample, but I was using a 120 chars per row standard in that project :P.

over 1 year ago ·

Hey, thanks for sharing. Great tip :)

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip