Image Processing in NodeJS with Jimp

Full code example: combining images, watermarking, fonts and text

npm i jimp

Working with Images in NodeJS

Consideration 1: Folder structure

project_folder/
raw/
image1.jpg
image2.jpg
...

active/
export/
generate_image.js

Consideration 2: External Image Libraries

Consideration 3: Public static folder with NodeJS Express

app/
public
static
routes
views
app.js
...
app.use('/exported-images', express.static('static'));
//development URL
http://localhost:3010/exported-images
//production URL
https://<your_domain>:3010/exported-images

Our Watermark and Text Jimp Script

The Script

Defining variables

Cloning Raw and Opening Active Image

Jimp.read(imgRaw)
.then(tpl => (tpl.clone().write(imgActive)))
.then(() => (Jimp.read(imgActive)))

Combining Watermark Image

.then(tpl => (
Jimp.read(imgLogo).then(logoTpl => {
logoTpl.opacity(0.2);
return tpl.composite(
logoTpl,
512-75,
512,
[Jimp.BLEND_DESTINATION_OVER]);
});
)

Loading our Text Font

.then(tpl => (
Jimp.loadFont(Jimp.FONT_SANS_32_WHITE
.then(font => ([tpl, font]))
))

Printing Text on Our Template

.then(data => {
tpl = data[0];
font = data[1];
return tpl.print(
font,
textData.placementX,
textData.placementY,
{
text: textData.text,
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
alignmentY: Jimp.VERTICAL_ALIGN_MIDDLE
},
textData.maxWidth,
textData.maxHeight);
})

Exporting and Post Processing

.then(tpl => (tpl.quality(100).write(imgExported)))   .then(tpl => {
console.log('exported file: ' + imgExported);
})
.catch(err => {
console.error(err);
});

Where to go from here

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

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