Scheepers de Bruin
Scheepers de Bruin

Reputation: 23

Stitching images with append() in graphicsmagick

I have a large number of images stored on a separate server that needs to be displayed on a single page as a mosaic of some sort where the individual elements may be shown or hidden dynamically.

These images should be fetched, resized and then stitched together as a sprite, and used as background images on divs. Fetching and resizing is a non-issue at this point, as the biggest hurdle is understanding the append method, or rather how to add images to a set, in order to use said method.

According to the docs:

gm("img.png").append(ltr)

should:

Append a set of images

How do I get multiple images into a "set"?

Upvotes: 2

Views: 2719

Answers (2)

nalply
nalply

Reputation: 28717

Let's say images is an array of path strings like this:

[ "/home/user/first.jpg", "/home/user/a.png", "/home/user/another.gif" ];

then this should work:

var gm = require('gm');

var gmstate = gm(images[0]);
for (var i = 1; i < images.length; i++) gmstate.append(images[i]);

// finally write out the file asynchronously
gmstate.write('/home/user/result.png', function (err) {
  if (!err) console.log('Hooray!');
});

The idea is:

  1. Start with a graphicsmagick state variable gmstate
  2. Append to it in a loop synchronously.
  3. write() does the real work, and this asynchronously.

This is equivalent to gm('first').append('second').append('third')....append('last').

Perhaps it is possible to start with an empty state: var gmstate = gm();.

I have to admit that the @ filelist hack in LeeNX's answer is a lot easier if you have a list in a file, but if you don't...?

EDIT: If you need to append the images horizontally, add a second parameter true to append(), like this:

gmstate.append(image, true);

Source: Documentation for append()

Upvotes: 4

LeeNX
LeeNX

Reputation: 14

Best I could do, was as follows ...

var gm = require('gm')

gm('@images.txt')
  .append()
  .write('crazy.png', function (err) {
    if (!err) console.log('crazytown has arrived');
  })

Where images.txt is a list of images to append.

Have not yet been able to figure out how to pass a set of images other than an image list file.

Got the idea from the website - http://www.graphicsmagick.org/GraphicsMagick.html

When running a commandline utility, you can prepend an at sign @ to a filename to read a > list of image filenames from that file. This is convenient in the event you have too many > image filenames to fit on the command line.

Hope that helps LeeT

Upvotes: 0

Related Questions