Godwin Ekuma I learn so that I can solve problems.

Image processing with Node and Jimp

3 min read 985

Image Processing with Node and Jimp

If your web application supports user-uploaded images, you probably need to transform them to fit the design specification of your app.

JavaScript Image Manipulation Program (Jimp) allows you to easily manipulate and transform your images into any required format, style, or dimension. It also optimizes images for minimal file size, ensures high visual quality for an improved user experience, and reduces bandwidth.

With Jimp, you can resize and crop images, convert them to the image format that fits your needs, and apply filters and effects. In this tutorial, we’ll go over how the library works and describe some common use cases for Jimp image manipulation.

Installation

npm install --save jimp

Jimp can only be used on a limited range of image formats. Before you start working with the library, you’ll want to make sure it supports the formats you plan to include in your app.

Supported types include:

  • @jimp/jpeg
  • @jimp/png
  • @jimp/bmp
  • @jimp/tiff
  • @jimp/gif

Basic use

Jimp offers both callback- and Promise-based APIs for manipulating images. For the purpose of this post, we’ll use Jimp’s Promise API.

​​The static Jimp.read​ method accepts an image as an input. The input could be the location of an image file in the file system, a web address (URL), dimension (width and height), Jimp instance, or buffer. Then, it returns a Promise.

Jimp.read('http://www.example.com/path/to/lenna.jpg')
  .then(image => {
    // Do stuff with the image.
  })
  .catch(err => {
    // Handle an exception.
  });

Resizing and cropping images

Resizing

Jimp’s resize() method alters the height and/or width of an image via a two-pass bilinear algorithm.

Syntax:

resize( w, h[, mode] )

Example:

const Jimp = require('jimp');
async function resize() {
  // Read the image.
  const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg');
  // Resize the image to width 150 and heigth 150.
  await image.resize(150, 150);
  // Save and overwrite the image
  await image.writeAsync(`test/${Date.now()}_150x150.png`);
}
resize();

Original image:

Original Image of a Sofa, Coffee Table, and Pillows Before Jimp Image Manipulation

Resized image:

Resized Image of a Sofa, Coffee Table, and Pillows

Jimp.AUTO can be passed as the value for the height or width and the image will be resized accordingly while maintaining aspect ratio. You cannot pass Jimp.AUTO as the value for both height and width.

If no resizing algorithm is passed, Jimp uses Jimp.RESIZE_BILINEAR as the default resizing algorithm. Other resizing algorithms that Jimp allows include:

  • Jimp.RESIZE_NEAREST_NEIGHBOR;
  • Jimp.RESIZE_BILINEAR;
  • Jimp.RESIZE_BICUBIC;
  • Jimp.RESIZE_HERMITE;
  • Jimp.RESIZE_BEZIER;

Crop

The crop() function is used to crop an image to specified x and y coordinates and dimensions.

Syntax:

crop( x, y, w, h)

Example:

async function crop() {
  // Read the image.
  const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg');
  await image.crop(500, 500, 150, 150);
  // Save and overwrite the image
  await image.writeAsync(`test/${Date.now()}_crop_150x150.png`);
}
crop()

Cropped image:

Cropped Image of a Sofa, Coffee Table, and Pillows

Modifying image shape and style

Rotate

The rotate() method rotates an image clockwise by a given number of degrees. The dimensions of the image remain the same.



Syntax:

rotate( deg[, mode] );

Example:

async function rotate() {
  // Read the image.
  const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg');
  await image.rotate(45);
  // Save and overwrite the image
  await image.writeAsync(`test/${Date.now()}_rotate_150x150.png`);
}
rotate()

Output:

Rotated Image of a Sofa, Coffee Table, and Pillows

Flip

The flip() method flips an image either horizontally or vertically. The default setting is to flip the image horizontally.

Syntax:

image.flip( horz, vert )

Example:

async function flip() {
  // Read the image.
  const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg');
  await image.flip(true, false);
  // Save and overwrite the image
  await image.writeAsync(`test/${Date.now()}_flip_150x150.png`);
  console.log("flipped")
}
flip()

Output:

Flipped Image of a Sofa, Coffee Table, and Pillows

Opacity

The opacity() method multiplies the opacity of each pixel by a factor within the range of 0 and 1.

Syntax:

opacity( f );

Example:

async function opacity() {
  // Read the image.
  const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg');
  await image.opacity(.5);
  // Save and overwrite the image
  await image.writeAsync(`test/${Date.now()}_opacity_150x150.png`);
}

Output:

Opaque Image of a Sofa, Coffee Table, and Pillows

Applying image effects and filters

Grayscale

The greyscale modifier desaturates or removes color from an image and turns it to grayscale.

Syntax:

greyscale();
>

Example:

async function greyscale() {
  // Read the image.
  const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg');
  await image.greyscale();
  // Save and overwrite the image
  await image.writeAsync(`test/${Date.now()}_greyscale_150x150.png`);
}
greyscale()

Output:

Grayscale Image of a Sofa, Coffee Table, and Pillows

Blur

The blur() method blurs an image by r pixels using a blur algorithm that produces an effect similar to a Gaussian blur, only much faster.

Syntax:

blur(r) // fast blur the image by r pixels

Example:

async function blur() {
  // Read the image.
  const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg');
  await image.blur(20);
  // Save and overwrite the image
  await image.writeAsync(`test/${Date.now()}_blur_150x150.png`);
}
blur()

Output:

Blurred Image of a Sofa, Coffee Table, and Pillows

Image and text overlays

Image overlay

The composite() method overlays an image over another Jimp image at x, y.

Syntax:

composite( src, x, y, [{ mode, opacitySource, opacityDest }] );  

Example:

async function waterMark(waterMarkImage) {
  let  watermark = await Jimp.read(waterMarkImage);
  watermark = watermark.resize(300,300);
  const image = await Jimp.read('https://images.pexels.com/photos/298842/pexels-photo-298842.jpeg');
 watermark = await watermark
  image.composite(watermark, 0, 0, {
    mode: Jimp.BLEND_SOURCE_OVER,
    opacityDest: 1,
    opacitySource: 0.5
  })
  await image.writeAsync(`test/${Date.now()}_waterMark_150x150.png`);
}
waterMark('https://destatic.blob.core.windows.net/images/nodejs-logo.png');

Output:

A Sofa, Coffee Table, and Pillows

Text overlay

You can write text on an image with the print() API. Jimp supports only the Bitmap font format (.fnt). Fonts in other formats must be converted to .fnt to be compatible with Jimp.

Example:

async function textOverlay() {
  const font = await Jimp.loadFont(Jimp.FONT_SANS_32_BLACK);
  const image = await Jimp.read(1000, 1000, 0x0000ffff);

  image.print(font, 10, 10, 'Hello World!');
}

textOverlay();

Output:

A Sofa, Coffee Table, and Pillows

Learn more about Jimp

We’ve only scratched the surface of use cases for Jimp. If you’re considering using Jimp as your primary image processor, check out the full documentation on the official GitHub and npm pages.

200’s only Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third party services are successful, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. .
Godwin Ekuma I learn so that I can solve problems.

2 Replies to “Image processing with Node and Jimp”

Leave a Reply