Search code examples
meteorgraphicsmagickcollectionfs

CollectionFS get image dimensions before transformation


I would like to resize image upon upload with Meteor CollectionFS. But I would like to resize based on image dimensions. For example, I want to resize image that is 1000x500 into 1024x512, but 60x100 into 64x128 - for that I need to know source dimensions.

I am basing my code on one provided by CollectionFS documentation:

var createThumb = function(fileObj, readStream, writeStream) {
  // Transform the image into a 10x10px thumbnail
  gm(readStream, fileObj.name()).resize('10', '10').stream().pipe(writeStream);
};

how do I get source dimensions here, to make my resize target dynamic? Maybe there are some graphicsmagick function?


Solution

  • There's an async GraphicsMagick function for returning the size (dimensions) of the image.

    gm(readStream).size({ bufferStream: true }, function(err, value) {
        var w = 100, h = 100;
    
        //modify logic here to set the desired output width/height, based on the source width/height
        if (value.width == 60 && value.height == 100) {
             w = 64;
             h = 128;
        }
    
        //"this" is the gm context, so you can chain gm functions to "this" inside the size callback.
        this.resize(w, h).stream().pipe(writeStream);
    });
    

    Notes from the gm npm package page on Github regarding this:

    GOTCHA: when working with input streams and any 'identify' operation (size, format, etc), you must pass "{bufferStream: true}" if you also need to convert (write() or stream()) the image afterwards NOTE: this buffers the readStream in memory!