Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS gm getting image size synchronously

I'm using gm and trying to process images according to it's size. Since "size" getter needs callback function, I can't use size in following lines.

What I want to do is like that:

function processImage(url) {
    var img = gm(this.getImgStream(url));

    var width, height;
    img.size(function(err, val) {
        width = val.width;
        height = val.height;
    });

    // I want to use width here, but it's undefined when this line is executed.
    if (width > 500) width = 500;
    return img.resize(width)
}

I want to use width in following resize method. Is there any way to get size synchronously or wait for a callback to complete? I don't want to use ivars as long as possible.

like image 620
taichino Avatar asked Oct 29 '13 05:10

taichino


2 Answers

Since img.size() is asynchronous, you can't do the operation synchronously (which means you also can't use return for a return value). Therefore, you need img.size() to finish before you can do anything else. You can either assign a callback within the operation, or pass callbacks around:

function processImage(url, callback) {
  var img = gm(this.getImgStream(url));

  var width, height;
  img.size(function(err, val) {
    width = val.width;
    height = val.height;

    callback(err, width, height);
  });
};

processImage(url, function(err, width, height) {
  if (width > 500) width = 500;
  img.resize(width);
});
like image 150
hexacyanide Avatar answered Sep 22 '22 04:09

hexacyanide


You can use the "image-size" npm package

var sizeOf = require('image-size');
var dimensions = sizeOf("/pathofimage/image.jpg");
console.log(dimensions.width, dimensions.height);
like image 22
Priya Avatar answered Sep 20 '22 04:09

Priya