In this article we will explore a tool called JIMP, which is used for image processing in Node JS.
To get started, we first need to install JIMP in our project, for this use this command
npm install --save jimp
This command will add JIMP to your dependencies.
let Jimp = require('jimp')
Jimp.read('YOUR_IMAGE.PNG')
.then(YOUR_IMAGE=> {
return YOUR_IMAGE
.resize(128, 128) // RESIZE IMAGE TO SPECIFIC RESOLUTION
.quality(50) // TO SET THE QUALITY OF IMAGE
.write('YOUR-IMAGE-ALTERED.jpg'); //TO SAVE YOUR IMAGE
})
.catch(e => {
console.error(e);
});
This reads your image , alters it according to specification and writes it in a new/same location.
Jimp.read('http://www.techjupyter.com/YOUR_IMAGE.jpg')
.then(image => {
// Alter your image here
})
.catch(err => {
// Catch an error
});
Suppose this is an image on which we want to write text, in this image, inside the rectangle we want our text to be manipulated, so how do we go about it?
async function alterTextInImage() {
const image = await Jimp.read('YOUR_IMAGE.png');
const font = await Jimp.loadFont(Jimp.FONT_SANS_16_BLACK);
image.print(font, 63, 90, {
text: "RANDOM CENTER TEXT",
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
alignmentY: Jimp.VERTICAL_ALIGN_CENTER
}, 548, 102);
await image.writeAsync(`YOUR_IMAGE_ALTERED.png`);
}
Now our text appears something like this:
Now if we check out Text it should start from (548-63)/2 = 242 , and it does if we check the co-ordinate from any image editing tool.
Jimp.HORIZONTAL_ALIGN_LEFT;
Jimp.HORIZONTAL_ALIGN_CENTER;
Jimp.HORIZONTAL_ALIGN_RIGHT;
Jimp.VERTICAL_ALIGN_TOP;
Jimp.VERTICAL_ALIGN_MIDDLE;
Jimp.VERTICAL_ALIGN_BOTTOM;
If you liked this article or found it useful, you can support the author by commenting below!