Question

I am using the gm Node module for cropping and making thumbnails of images. Here's what I'm trying to do...

var img = gm("./myImage.jpg");
var thmb;

if(options.crop)
   img = img.crop(100, 50, 10, 10);

if(options.resize)
   thmb = img.resize(240);

img.stream(callback);

if(thmb)
   thmb.stream(callback2);

Expected result:

The above code should output two images ('img' and 'thmb'). 'img' should be cropped version of the original image and 'thmb' should be the cropped AND resized version of original.

Actual result

'img' output is cropped as expected but the 'thmb' is ONLY a resized version of the original image. It's not cropped as expected. What am I doing wrong?

Was it helpful?

Solution

The way gm works you have to use one chain of transformations per desired output, even if the input is the same. So if you want to do A and B on a file foo.jpg, and put the output in one file, and do only B on the same input file but put the output in a different file, you'd have to do:

var gm = require("gm");
gm("./foo.jpg").A().B().stream(...);
gm("./foo.jpg").B().stream(...);

The operations on the objects returned by gm return the same object they ware called on. So img.crop(...) === img is true. The example uses crop but this is generally true for other operations too. So if you do thmb = img.resize(...) then after this operation thmb === img is true. This is why you have to create two separate objects with gm(...).

So somethig like this should do what you want:

var gm = require("gm");
var fs = require("fs");

options = {
    resize: true,
    crop: true
};

var img = gm("./myImage.jpg");
var thmb = options.resize ? gm("./myImage.jpg") : undefined;

if(options.crop)
   img = img.crop(500, 50, 10, 10);
   if (thmb)
       thmb = thmb.crop(500, 50, 10, 10);

if(options.resize)
    thmb = thmb.resize(240);

img.stream(function (err, stdout, stderr) {
    stdout.pipe(fs.createWriteStream("./out.jpg"));
});


if(thmb)
   thmb.stream(function (err, stdout, stderr) {
       stdout.pipe(fs.createWriteStream("./thumb.jpg"));
   });

I've changed the crop parameters to give a width of 500 because resizing to a width of 240 after cropping to a width of 100 does nothing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top