如何用Graphicsmagick创建缩略图?

时间:2014-02-06 13:04:54

标签: javascript node.js

我是node.js的新手,我正在尝试使用GraphicsMagic。我已经在我的windows pc中安装了GraphicsMagic,并且还安装了npm install的gm模块。我能够获得完整的图像,但无法使用以下代码创建拇指。任何人都可以帮助我朝正确的方向前进吗?

var express = require('express');
var app = express(); 
var fs = require('fs');
var gm = require('gm');


app.configure(function () {
    app.use(express.logger('dev'));                             
    app.use(express.bodyParser());                          
    app.use(express.methodOverride());                      
});

app.listen(8080);
console.log("App listening on port 8080");


app.post('/upload', function (req, res) {
    fs.readFile(req.files.image.path, function (err, data) {
        var imageName = req.files.image.name;
        if (!imageName) {
            console.log("There was an error");
            res.redirect("/");
            res.end();
        } else {
            var newPath = __dirname + "/uploads/fullsize/" + imageName;
            var thumbPath = __dirname + "/uploads/thumbs/" + imageName;
            fs.writeFile(newPath, data, function (err) {
                gm(newPath)
                    .resize(240, 240)
                    .noProfile()
                    .write(thumbPath, function (err) {
                        if (!err) console.log('done');
                        res.redirect("/uploads/thumbs/"+imageName);
                    });
            });


        }
    });
});

app.get('/uploads/thumbs/:file', function (req, res) {
    file = req.params.file;
    var img = fs.readFileSync(__dirname + "/uploads/thumbs/" + file);
    res.writeHead(200, {'Content-Type': 'image/jpg' });
    res.end(img, 'binary');

});


app.get('*', function (req, res) {
    res.sendfile('./views/index.html'); // load the single view file (angular will handle the page changes on the front-end)
});

的index.html:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="image" />
    <input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

0 个答案:

没有答案