使用NodeJS gm同步获取图像大小

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

我希望在以下的调整大小方法中使用宽度。有没有办法同步获取尺寸或等待回调完成?只要可能,我不想使用实例变量。

3个回答

10

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

7
你可以使用 "image-size" npm 包。
var sizeOf = require('image-size');
var dimensions = sizeOf("/pathofimage/image.jpg");
console.log(dimensions.width, dimensions.height);

1
您可以将 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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接