Search code examples
node.jsmodulebuffersharp

How do i access an image from the node.js sharp module buffer


I'm new to node.js and web development and have a question regarding the node.js sharp module. I want to resize/crop an image using the node.js sharp module, store it to a buffer and access it afterwards. After reading the Sharp API I came up with this code example.

sharp('img.jpg').extract(extract).resize(height, width).toBuffer(function (err, data, info) {img = data;});

I thought that the variable img now contains my new image. My first question would be whether my assumption is correct. If this is correct, how can i display the new image on my website? If possible, I would like to use an HTML img tag. But if there are better and easier ways, feel free to let me know. I don't want to store the image to a local file.

Thanks for your help!


Solution

  • That's correct. You first need to save your image on your disk with fs for example ->

    const   saveImageOnDisk = (base64Image, imageName) => 
    {
        const   buf = new Buffer(base64Image.replace(/^data:image\/\w+;base64,/, ''), 'base64');
    
        fs.writeFile(`./${imageName}.png`, buf, {encoding: 'base64', flag: 'w'}, err => console.warn(err));
    };
    

    And then, you can try to access this image by doing some operation with Sharp (ex. on a node server to display the image)

    exports.getImage = (req, res) =>
    {
        const   fileName = `./${req.params.image}`;
        const   width = 200;
        const   height = 200;
    
        sharp(fileName)
        .resize(height, width)
        .toBuffer()
        .then((data) =>
        {
            //To display the image
            res.writeHead(200, {
                'Content-Type': 'image/png',
                'Content-Length': data.length
            });
            return (res.end(data));
        })
        .catch(err => console.log(err));
    };
    

    So, with a route like this

    app.route('/myImages/:image').get(Methods.getImage);
    

    You can access your image with you simple url -> http://yourserver.xyz/myImages/imageX