Question

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.

Was it helpful?

Solution

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);
});

OTHER TIPS

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

You could also wrap GM's size() function in a promise to make it async

async getImageSize() {
    return new Promise((resolve, reject) => {
        gm(imageFilePath)
        .size((error, size) => {
            if (error) {
                console.error('Failed to get image size:', error);
                reject(error);
            } else {
                resolve(size);
            }
        });
    });
}

// Get the image size synchronously:
const size = await this.getImageSize();
console.log("Parent got size of " + size.width);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top