node.js中使用imagemagick进行图片裁剪压缩

node.js中使用imagemagick进行图片裁剪压缩

  1. 安装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
    
  2. 安装GraphicsMagick for node http://aheckmann.github.com/gm/

     npm install gm
    
  3. 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'));
    

错误处理

  1. 如出现以下错误,请参考: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.
    
  2. 如果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
    
posted @ 2015-04-07 15:07  wayns  阅读(3468)  评论(0编辑  收藏  举报