node.js 对图片进行操作是要安装 gm 模块,而 gm 模块是通过调用系统的ImageMagick 或者GraphicsMagick 来处理图片的,在开发工程中,两种软件我都装过,但是只有GraphicsMagick测试通过,下面就以GraphicsMagick为例子来介绍方法:
1、在电脑上安装 GraphicsMagick ,在官网上下载安装即可,注意和自己系统匹配的安装包。
2、执行指令 ,安装gm模块
npm install gm --save
3、编写上传代码,文件的上传我这里使用了 formidable,安装方式就不再赘述,请参考相关文档,具体实现代码如下:
var formidable = require('formidable'),
    util = require('util'),fs=require('fs');
//系统相关操作
var System = require("../models/System");
var gm = require('gm');
var url = require('url');
/* GET users listing. */
router.post('/upload', function(req, res, next) {
//    获取传入参数
    var params = url.parse(req.url,true);
    var fileType = params.query.type;
    var fileKey = params.query.key;
    var form = new formidable.IncomingForm(),files=[],fields=[],docs=[];
    console.log('start upload');
    //存放目录
    var updatePath = "publichttps://cdn.html-js.cn/cms/upload/images/";
    var smallImgPath = "publichttps://cdn.html-js.cn/cms/upload/smallimgs/";
    var newFileName = "";
    form.uploadDir = updatePath;
    form.on('field', function(field, value) {
        fields.push([field, value]);
    }).on('file', function(field, file) {
        files.push([field, file]);
        docs.push(file);
        var typeKey = "others";
        var thisType = file.name.split('.')[1];
        var date = new Date();
        var ms = Date.parse(date);
        if(fileType == 'images'){
            typeKey = "img"
        }
        newFileName = typeKey + ms + "."+thisType;
        fs.rename(file.path,updatePath+newFileName,function(err){
            if(err){
                console.log(err)
            }else{
                // 图片缩放
                var input =  updatePath+newFileName;
                var out = smallImgPath+newFileName;
                if(fileType == 'images'){
                    if(fileKey == 'ctTopImg'){
                        gm(input).resize(190,125,'!').autoOrient().write(out, function (err) {
                            if (err) {
                                console.log(err);
                            } else {
                                console.log('done');
                            }
                        });
                    }
                }
            }
        })
    }).on('end', function() {
        console.log('-> upload done');
        res.writeHead(200, {
            'content-type': 'text/plain'
        });
        var out={Resopnse:{
            'result-code':0,
            timeStamp:new Date()
        },
            files:docs
        };
        var sout=JSON.stringify(out);
//        返回文件路径
        res.end('https://cdn.html-js.cn/cms/upload/smallimgs/'+newFileName);
    });
    form.parse(req, function(err, fields, files) {
        err && console.log('formidabel error : ' + err);
        console.log('parsing done');
    });
});
压缩文件主要是下面这一段:
gm(input).resize(190,125,'!').autoOrient().write(out, function (err) {
                            if (err) {
                                console.log(err);
                            } else {
                                console.log('done');
                            }
                        });
源码参考:
 
        
 
            
             
            
             
            
             
            
            