Skip to main content

Image processing with Node and Jimp

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 xy.
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.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...