Search code examples
node.jsimagenode-red

How to resize images in a node-red flow


I have a node red flow where i get some images from a REST API as binary buffers in png or jpg format.

Motivation: Some people do not pay attention and post very large pics to a blog service. Since the service is limited in its amount of storage for pics I want to listen to the stream of events and resize every incoming picture to "longest side = 1024" while keeping the aspect ratio like it is.

Now I have the binary objects as buffer in my flow - but how to resize an image in a node-red flow? I did search for half a day but did not find a node which is capable of doing that. Any ideas?


Solution

  • I ended up making jimp available publicly by adding the entry "jimp":"0.2.x", to the package.json dependencies and adding into functionGlobalContext in the settings.js:

    functionGlobalContext: {
           mcrypto:require('crypto'),
           Jimp:require('jimp')
    },
    

    Now I can easily use it in a function node by simply writing:

    var JIMP = global.get("Jimp");
    msg.image2 = {};
    JIMP.read(msg.payload).then(function(image) {
        msg.image.width = image.bitmap.width;
        msg.image.height = image.bitmap.height;
    
        if (image.bitmap.height > image.bitmap.width){
            if (image.bitmap.height > 800){
                image.resize(JIMP.AUTO, 800)
                msg.image2.width = image.bitmap.width;
                msg.image2.height = image.bitmap.height;
                image.getBuffer(image.getMIME(), onBuffer);
            }
        }
        else {
                if (image.bitmap.width > 800){
                image.resize(800, JIMP.AUTO)
                msg.image2.width = image.bitmap.width;
                msg.image2.height = image.bitmap.height;
                image.getBuffer(image.getMIME(), onBuffer);
            }
        }
    }).catch(function (err) {
        // handle an exception
        if (err) throw err;
    });
    
    function onBuffer (err, buffer) {
        if (err) throw err;
        msg.payload = buffer;
        node.send(msg);
    }
    
    return ;
    

    This way I solved my need. Better ideas welcome.