npm install --save jimpInclude JIMP in your JS file, and perform a simple read and write operation in JIMP :
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);
});
To read from a URL you can use:
Jimp.read('http://www.techjupyter.com/YOUR_IMAGE.jpg')
.then(image => {
// Alter your image here
})
.catch(err => {
// Catch an error
});
Now that we have covered basics on how to alter image, we can move to our main concern, which is altering text/manipulating text using JIMP.
Let's start by taking an example image and marking our co-ordinates. (You can find out co-ordinates of your desired position through MS Paint, or any other image editing tool).
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?
First we need to mark/find out the co-ordinate from where we want our text to begin , in this case, I want my text to be center aligned in the rectangle and it should never be outside the rectangle.
For this I will use Horizontal alignment as CENTER and give X co-ordinate as 63, Y co-ordinate as something above 102 (DECREASING Y) so I would give around 90 to Y co-ordinate so that my Text height can start from approximate 92th Y Co-ordinate and MAX Width X as 548 and MAX width Y as 102.
Now we will try running our code:
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 we can alter it slightly left or slightly below as per visual cleanliness and we are done!
We can set different ALIGNMENTS of our image
Jimp.HORIZONTAL_ALIGN_LEFT;
Jimp.HORIZONTAL_ALIGN_CENTER;
Jimp.HORIZONTAL_ALIGN_RIGHT;
Jimp.VERTICAL_ALIGN_TOP;
Jimp.VERTICAL_ALIGN_MIDDLE;
Jimp.VERTICAL_ALIGN_BOTTOM;
0 Comments