如何在Node.js中使用ImageMagick将图像类型转换为'jpg'

3

我在我的Node.js应用程序中使用ImageMagick。我已经按如下方式调整了图像的大小:

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

我希望我的代码可以将传入的图片转换为 jpg 格式。我该如何实现这个功能?


jimp npm包(完整的JavaScript)似乎能够很好地完成这项工作:https://github.com/oliver-moran/jimp/tree/master/packages/jimp - Contestosis
2个回答

3

为了使用这个解决方案,您需要使用easyimage包。这个包在运行时需要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。

1
你需要使用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()(虽然我肯定想知道它的确切用途)。感谢您的帮助。 - Radhika

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