Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Extending gm

aheckmann edited this page · 1 revision

Extending gm with your own custom methods is easy. All that’s necessary is adding your method to gm.prototype. For example, let’s write a sepia extension which will give any image a nice sepia tone.

var gm = require("gm")
gm.prototype.sepia = function(){
  this.modulate(115, 0, 100).colorize(7, 21, 50)
  return this
}

Hey, that looks pretty simple right? And you’d use it like so:

gm("path/to/img.png")
  .sepia()
  .write("iLoveSepiaAndSoShouldYou.png", function(err){ ... })

So let’s take a looky at what’s going on here. Within the sepia method, this refers to the current instance of gm so you have access to all of the other gm methods and extensions. We’re just utilizing two built in gm methods here to get the effect we want. Notice also that we return this, which let’s us retain the ability to continue chaining methods. We could return a little more elegantly too since, by convention, every method returns this:

var gm = require("gm")
gm.prototype.sepia = function(){
  return this.modulate(115, 0, 100).colorize(7, 21, 50)
}
Something went wrong with that request. Please try again.