8

我正在使用 gm 并尝试根据其大小处理图像。由于“size”getter 需要回调函数,所以我不能在以下几行中使用 size。

我想做的是这样的:

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

我想在以下调整大小方法中使用宽度。有什么方法可以同步获取大小或等待回调完成?我不想尽可能长时间地使用 ivars。

4

3 回答 3

9

由于img.size()是异步的,因此您不能同步执行操作(这意味着您也不能return用于返回值)。因此,您需要img.size()先完成,然后才能执行其他任何操作。您可以在操作中分配回调,也可以传递回调:

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);
});
于 2013-10-29T05:10:21.837 回答
6

您可以使用“图像大小”npm 包

var sizeOf = require('image-size');
var dimensions = sizeOf("/pathofimage/image.jpg");
console.log(dimensions.width, dimensions.height);
于 2014-08-12T09:17:09.030 回答
0

您还可以将 GM 的 size() 函数包装在一个 Promise 中以使其异步

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);
于 2021-11-26T14:32:13.777 回答