node.js中使用imagemagick进行图片裁剪压缩
-
安装imagemagick
sudo apt-get install imagemagick
or
wget http://www.imagemagick.org/download/ImageMagick.tar.gz tar zxvf ImageMagick.tar.gz cd ImageMagick ./configure --prefix=/usr/local make sudo make install
-
安装GraphicsMagick for node http://aheckmann.github.com/gm/
npm install gm
-
node.js代码
var fs, gm; gm = require('gm'); gm('./img/before.jpg').options({ imageMagick: true }).resize(130, 105).write('./img/after.jpg', function(err) { if (err) { return console.error(err); } return console.log('success'); });
使用文件流:
var fs, gm; gm = require('gm'); fs = require('fs'); gm(fs.createReadStream('./img/before.jpg')).options({ imageMagick: true }).resize(130, 105).stream().pipe(fs.createWriteStream('./img/after.jpg'));
处理网上图片:
var fs, gm, request; gm = require('gm'); fs = require('fs'); request = require('request'); gm(request('http://url_to_img.jpg')).options({ imageMagick: true }).resize(130, 105).stream().pipe(fs.createWriteStream('./img/after.jpg'));
错误处理
-
如出现以下错误,请参考: http://www.xgezhang.com/imagemagick_convert_problem.html
convert: no decode delegate for this image format `JPEG' @ error/constitute.c/ReadImage/501. convert: no images defined `img/after.jpg' @ error/convert.c/ConvertImageCommand/3212.
-
如果configure提示“configure: error: libltdl is required for modules build”,则yum search ltdl,然后(以CentOS 6.3 64bit 为例)
yum install libtool-ltdl.x86_64 yum install libtool-ltdl-devel.x86_64