【问题标题】:NodeJS gm getting image size synchronouslyNodeJS gm 同步获取图像大小
【发布时间】:2013-11-08 03:05:03
【问题描述】:

我正在使用 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。

【问题讨论】:

    标签: node.js asynchronous node-imagemagick


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      你可以使用“image-size”npm 包

      var sizeOf = require('image-size');
      var dimensions = sizeOf("/pathofimage/image.jpg");
      console.log(dimensions.width, dimensions.height);
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2016-08-16
          • 2014-03-02
          • 1970-01-01
          • 1970-01-01
          • 2016-02-29
          • 1970-01-01
          • 2023-03-09
          • 2017-03-29
          • 1970-01-01
          相关资源
          最近更新 更多