【问题标题】:How to convert image type to 'jpg' using imagemagick in node.js如何使用 node.js 中的 imagemagick 将图像类型转换为“jpg”
【发布时间】:2014-03-10 13:54:10
【问题描述】:

我在我的 node.js 应用程序中使用 imagemagick。我已将图像大小调整如下:

im.resize({
        format: 'jpg',
        srcPath: imagePath,
        dstPath: thumbPath,
        width: 220,
        }, function(err, stdout, stderr){
        //some code
       }
});

我希望我的代码将传入的图像转换为jpg。我怎样才能做到这一点?

【问题讨论】:

    标签: node.js imagemagick


    【解决方案1】:

    对于此解决方案,您需要使用 easyimage package 。这个包在下运行并且需要imagemagick(非常重要)。

    $npm install easyimage --save // saved in your package.json
    

    包含在您的代码中:

    var easyimg = require('easyimage');
    

    首先你需要得到原图的路径:

    tmp_path = 'path/to/image.svg';
    

    现在您更改“tmp_path”的扩展名:

    tmp_extless = tmp_path.replace('.svg','.png'); //be sure of include "."
    

    所以,tmp_path 是原始路径,tmp_extless 是我们未来镜像的路径。

    现在,easyimage 的魔力:

    easyimg.convert({src: tmp_path, dst: tmp_extless, quality: 80},
        function(err,stdout){ 
          if(stdout){ console.log('stdout', stdout);
            //here you can run a script to delete tmp_path
          }
        }
    );
    

    现在,您的新图像位于路径中:tmp_extless。 使用此方法,您不需要 writeFile 或 readFile。

    【讨论】:

      【解决方案2】:

      您需要writeFileSync 并通过匿名函数将您的数据输入。

      im.resize({
              format: 'jpg',
              srcPath: imagePath,
              dstPath: thumbPath,
              width: 220,
              }, function(err, stdout, stderr){
                  fs.writeFileSync('[filename].jpg', stdout,'binary'); //write the file here
             }
      });
      

      相信你也需要调用convert方法。

      im.convert(['originalfilename.originalextension', 'jpg:-'], 
      

      【讨论】:

      • .convert() 有效。显然不需要 writeFileSync()(尽管我肯定想知道它的确切用法)。感谢您的帮助。
      猜你喜欢
      • 2014-11-02
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      相关资源
      最近更新 更多