gm

GraphicsMagick for node

README


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+

  1. ``` js
  2. const fs = require('fs')
  3. const gm = require('gm').subClass({ imageMagick: '7+' });
  4. ```

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

  1. ``` js
  2. const fs = require('fs')
  3. const gm = require('gm').subClass({ imageMagick: true });
  4. ```

Specify the executable path


Optionally specify the path to the executable.

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

Basic Usage


  1. ``` js
  2. var fs = require('fs')
  3.   , gm = require('gm');

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

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

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

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

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

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

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

  48. // crazytown
  49. gm('/path/to/my/img.jpg')
  50. .flip()
  51. .magnify()
  52. .rotate('green', 45)
  53. .blur(7, 3)
  54. .crop(300, 300, 150, 130)
  55. .edge(3)
  56. .write('/path/to/crazy.jpg', function (err) {
  57.   if (!err) console.log('crazytown has arrived');
  58. })

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

  68. // creating an image
  69. gm(200, 400, "#ddff99f3")
  70. .drawText(10, 50, "from scratch")
  71. .write("/path/to/brandNewImg.jpg", function (err) {
  72.   // ...
  73. });
  74. ```

Streams


  1. ``` js
  2. // passing a stream
  3. var readStream = fs.createReadStream('/path/to/my/img.jpg');
  4. gm(readStream, 'img.jpg')
  5. .write('/path/to/reformat.png', function (err) {
  6.   if (!err) console.log('done');
  7. });


  8. // passing a downloadable image by url

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

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


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

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

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

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

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

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

  63. ```

Buffers


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

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

  10. /*
  11. A buffer can also be returned instead of a stream
  12. The first argument to toBuffer is optional, it specifies the image format
  13. */
  14. gm('img.jpg')
  15. .resize(100, 100)
  16. .toBuffer('PNG',function (err, buffer) {
  17.   if (err) return handle(err);
  18.   console.log('done!');
  19. })
  20. ```

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:

  1. ``` sh
  2. gm "convert" "label:Offline" "PNG:-"
  3. ```

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

  1. ``` js
  2. gm()
  3. .label('Offline')
  4. .stream();
  5. ```

would yield:

  1. ``` sh
  2. gm "convert" "-label" "\"Offline\"" "PNG:-"
  3. ```

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

  1. ``` js
  2. gm()
  3. .out('label:Offline')
  4. .stream();
  5. ```

which correctly yields:

  1. ``` sh
  2. gm "convert" "label:Offline" "PNG:-"
  3. ```

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 usinggm().identify(format, callback).
For example,

  1. ``` js
  2. gm('img.png').format(function (err, format) {

  3. })

  4. // is equivalent to

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

  6. })
  7. ```

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

Platform differences



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.
  - 2) gm(stream || buffer, [filename]) You may also pass a ReadableStream or Buffer as the first argument, with an optional file name for format inference.
  - 3) 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


  - getters
    - size - returns the size (WxH) of the image
    - orientation - returns the EXIF orientation of the image
    - format - returns the image format (gif, jpeg, png, etc)
    - depth - returns the image color depth
    - color - returns the number of colors
    - res   - returns the image resolution
    - filesize - returns image filesize
    - identify - returns all image data available. Takes an optional format string.

  - manipulation
    - adjoin
    - affine
    - antialias
    - append
    - authenticate
    - autoOrient
    - average
    - backdrop
    - bitdepth
    - blackThreshold
    - bluePrimary
    - blur
    - border
    - borderColor
    - box
    - channel
    - charcoal
    - chop
    - clip
    - coalesce
    - colors
    - colorize
    - colorMap
    - colorspace
    - comment
    - compose
    - compress
    - contrast
    - convolve
    - crop
    - cycle
    - deconstruct
    - delay
    - define
    - density
    - despeckle
    - dither
    - displace
    - display
    - dispose
    - dissolve
    - edge
    - emboss
    - encoding
    - enhance
    - endian
    - equalize
    - extent
    - file
    - filter
    - flatten
    - flip
    - flop
    - foreground
    - frame
    - fuzz
    - gamma
    - gaussian
    - geometry
    - gravity
    - greenPrimary
    - highlightColor
    - highlightStyle
    - iconGeometry
    - implode
    - intent
    - interlace
    - label
    - lat
    - level
    - list
    - limit
    - log
    - loop
    - lower
    - magnify
    - map
    - matte
    - matteColor
    - mask
    - maximumError
    - median
    - minify
    - mode
    - modulate
    - monitor
    - monochrome
    - morph
    - mosaic
    - motionBlur
    - name
    - negative
    - noise
    - noop
    - normalize
    - noProfile
    - opaque
    - operator
    - orderedDither
    - outputDirectory
    - paint
    - page
    - pause
    - pen
    - ping
    - pointSize
    - preview
    - process
    - profile
    - progress
    - quality
    - raise
    - rawSize
    - randomThreshold
    - recolor
    - redPrimary
    - region
    - remote
    - render
    - repage
    - resample
    - resize
    - roll
    - rotate
    - sample
    - samplingFactor
    - scale
    - scene
    - scenes
    - screen
    - segment
    - sepia
    - set
    - setFormat
    - shade
    - shadow
    - sharedMemory
    - sharpen
    - shave
    - shear
    - silent
    - solarize
    - snaps
    - stegano
    - stereo
    - strip _imagemagick only_
    - spread
    - swirl
    - textFont
    - texture
    - threshold
    - thumb
    - tile
    - transform
    - transparent
    - treeDepth
    - trim
    - type
    - update
    - units
    - unsharp
    - usePixmap
    - view
    - virtualPixel
    - visual
    - watermark
    - wave
    - whitePoint
    - whiteThreshold
    - window
    - windowGroup

  - drawing primitives
    - draw
    - drawArc
    - drawBezier
    - drawCircle
    - drawEllipse
    - drawLine
    - drawPoint
    - drawPolygon
    - drawPolyline
    - drawRectangle
    - drawText
    - fill
    - font
    - fontSize
    - stroke
    - strokeWidth
    - setDraw

  - image output
    - write - writes the processed image data to the specified filename
    - stream - provides a ReadableStream with the processed image data
    - toBuffer - returns the image as a Buffer instead of a stream

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)

  1. ``` js
  2. gm.compare('/path/to/image1.jpg', '/path/to/another.png', function (err, isEqual, equality, raw, path1, path2) {
  3.   if (err) return handle(err);

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

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

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

  10.   // print file paths
  11.   console.log(path1, path2);
  12. })
  13. ```

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


  1. ``` js
  2. gm.compare('/path/to/image1.jpg', '/path/to/another.png', 1.2, function (err, isEqual) {
  3.   ...
  4. })
  5. ```

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


  1. ``` js
  2. var options = {
  3.   file: '/path/to/diff.png',
  4.   highlightColor: 'yellow',
  5.   tolerance: 0.02
  6. }
  7. gm.compare('/path/to/image1.jpg', '/path/to/another.png', options, function (err, isEqual, equality, raw) {
  8.   ...
  9. })
  10. ```

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])

  1. ``` js
  2. gm('/path/to/image.jpg')
  3. .composite('/path/to/second_image.jpg')
  4. .geometry('+100+150')
  5. .write('/path/to/composite.png', function(err) {
  6.     if(!err) console.log("Written composite image.");
  7. });
  8. ```

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)

  1. ``` js
  2. gm('/path/to/image.jpg')
  3. .montage('/path/to/second_image.jpg')
  4. .geometry('+100+150')
  5. .write('/path/to/montage.png', function(err) {
  6.     if(!err) console.log("Written montage image.");
  7. });
  8. ```

Contributors


Inspiration

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

Plugins


Tests

npm test

To run a single test:

  1. ```
  2. npm test -- alpha.js
  3. ```

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.