DEV Community

Cover image for Image processing with Node and Jimp
Brian Neville-O'Neill
Brian Neville-O'Neill

Posted on • Originally published at blog.logrocket.com on

Image processing with Node and Jimp

Written by Godwin Ekuma✏️

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

LogRocket Free Trial Banner

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.
  });
Enter fullscreen mode Exit fullscreen mode

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] )
Enter fullscreen mode Exit fullscreen 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();
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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] );
Enter fullscreen mode Exit fullscreen 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()
Enter fullscreen mode Exit fullscreen mode

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 )
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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 );
Enter fullscreen mode Exit fullscreen mode

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`);
}
Enter fullscreen mode Exit fullscreen mode

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();
>
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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 }] );  
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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 show GraphQL requests in production

While GraphQL has some features for debugging requests and responses, making sure GraphQL reliably serves resources to your production app is where things get tougher. If you’re interested in ensuring network requests to the backend or third party services are successful, try LogRocket.

Alt Text

LogRocket is like a DVR for web apps, recording literally everything that happens on your site. Instead of guessing why problems happen, you can aggregate and report on problematic GraphQL requests to quickly understand the root cause. In addition, you can track Apollo client state and inspect GraphQL queries' key-value pairs.

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. Start monitoring for free.


The post Image processing with Node and Jimp appeared first on LogRocket Blog.

Top comments (0)