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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...