Having trouble working with images?

Working with files are always bit trickier because reading/writing files are not something we do very frequently like using loops or declaring variables.

Here, I’m going to walk you through where you’ve two images and you want to put one image on top of another.

We are going to merge two images and create a beautiful image out of it.

Chaliye shuru karte hain

To merge the two images, we are going to use .
Install jimp using this command, npm i jimp or yarn add jimp.

After successfully installing jimp,

const jimp = require('jimp');
const jimpsArr = [];
jimpsArr.push(jimp.read('./image.jpg'));
jimpsArr.push(jimp.read('./logo.jpg));
await Promise.all(jimpsArr).then(async(data)=>{
data[0].composite(data[1],x,y)
});

Here we are reading the images using jimp.read(), it’ll create promises.
Pushing the promises in jimpsArr which we created at the beginning of the code.

Note:- You can read the images using urls also.

After creating an array of promises, we are going to resolve them using Promise.all

After the promises are resolved, we are going to put the logo over image at the defined co-ordinates. Co-ordinates are x and y here.

image.composite() is where the magic happens.
data[0] is an image and data[1] is a logo we want to place at (x,y) coordinates.

Once you are done with calling composite function of jimp, you’ve your image ready with the logo on top of it. Now the only thing you’ve to do is write that image in your directory or create buffer of that image and upload it wherever you want.

// writing the image in the current directoryawait Promise.all(jimpsArr).then(async(data)=>{
data[0].composite(data[1],x,y)
data[0].write('./final-image.jpg');
});

OR

// generating buffer out of it.await Promise.all(jimpsArr).then(async(data)=>{
data[0].composite(data[1],x,y)
const buffer = await data[0].getBufferAsync(mime)
});

Note:- Here I’ve taken two images for the sake of simplicity, you can take more than 2 images also.

Above is the image which I’ve created using and ,

Thank you!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store