Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image Resize on the fly from Amazon S3 using Node.js

I've a bucket with many images and I want to resize one of them on the fly, from a buffer returned from Amazon S3 getObject() method, but I can't find a library for resizing directly from memory buffer. Thumbbot and Imagemagick read the file from disk and that's not what I need!

This is a sample code:

exports.resizeImage = function(req, res) {
    bucket.getObject({Key: 'image.jpg'}, function(err, data){
        if (err) throw err;
        var image = resizeImage(data.Body);//where resize image is a method or a library that I need to call
        res.writeHead(200, {'Content-Type': data.ContentType });
        res.end(image); //send a resized image buffer
    });
};

I appreciate any help, Thanks

like image 460
Ragnar Avatar asked Mar 26 '26 13:03

Ragnar


1 Answers

I found the solution using gm library for node js

var gm = require('gm').subClass({ imageMagick: true });

exports.resizeImage = function(req, res) {
    bucket.getObject({Key: 'image.jpg'}, function(err, data){
        if (err) throw err;
        gm(data.Body, 'ok.jpg')
            .size({bufferStream: true}, function(err, size) {
                this.resize(200, 200);
                this.toBuffer('JPG',function (err, buffer) {
                    if (err) return handle(err);
                    res.writeHead(200, {'Content-Type': data.ContentType });
                    res.end(buffer);
                });
            });
    });
};
like image 106
Ragnar Avatar answered Mar 29 '26 04:03

Ragnar