NodeJS Image Manipulation (Using JIMP)

Fabio Kounang
3 min readJul 31, 2022

--

Keep coding and be happy :D

Prerequisite :

  1. NodeJS
  2. HTML

So I’ve been given an assignment where I should generate a QR Code but with a little description on the image like the example below.

So I research on how to do this with NodeJS and it turns out I found a package named jimp. It’s a pretty good package and its documentation is very well documented. So I decided to use jimp. Let’s dive in!

  1. Generate a NodeJS Project
npm init -y

2. Install express and jimp

npm install express jimp

3. Create a js file, for me, I usually go with app.js

4. In the app.js file

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const Jimp = require('jimp');

app.listen(() => {
console.log('Image manipulation server is listening to port ' + port);
});

5. Create an endpoint (/qr)

app.post('/qr', async (req, res, next) => {
const image = await Jimp.read(req.body.url);
const font = await Jimp.loadFont(Jimp.FONT_SANS_16_BLACK);
// in my case i wanna make my qr bigger wanna resize your image
image.resize(350, 350, async (err, value) => {
value.print(font, 0, 5, {
text: 'your top custom text',
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER
}, value.getWidth());
value.print(font, 0, 325, {
text: 'your bottom custom text',
alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER
}, value.getWidth());
const base64 = await value.getBase64Async(value.getMIME());
res.send(base64);
});

Explanation:

  1. Read URL image using Jimp.read method
  2. Load the font you want to use with the Jimp.loadFont method
  3. In my case, i want to make my QR bigger so I'm using an image.resize method. If you don't want to make it bigger just use the image variable instance to print your text and generate base64 (replace all value. with image.)
  4. Image.resize.for the first parameter is your font choice, the second parameter is your X axis start position, the third parameter is your Y axis. The fourth parameter can text either string for your text or an object with a lot of custom properties in it. So I use it to config my custom text and my X alignment so my text is centered in the middle of my image (top and bottom). The fifth parameter takes you the max width of the image. If your image width is 350, then value.getWidth() will be 350
  5. Then when you’re done, generate a base64 image using the getBase64Async method. And it takes a mime parameter that you can get with the getMIME() method.
  6. Response to your client-side (for me I was using Angular) and then I just show the QR with img tag
<img src="your base 64">

Result :

That’s it! I hope it helps :D

--

--

Fabio Kounang
Fabio Kounang

Written by Fabio Kounang

💻 Software Engineer, passionate in tech industry

No responses yet