Image processing with Node and Jimp
Tags: jimp, node, javascript, tutorial
Published: 2020-02-18 17:01:15

---
title: Image processing with Node and Jimp
published: true
date: 2020-02-14 14:00:17 UTC
tags: jimp,node,javascript,tutorial
canonical_url: https://blog.logrocket.com/image-processing-with-node-and-jimp/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/v9q23477jpx21epng1oa.png
---
**Written by [Godwin Ekuma](https://blog.logrocket.com/author/godwinekuma/)**✏️

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)](https://github.com/oliver-moran/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](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

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

```jsx
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:

```jsx
resize( w, h[, mode] )
```

Example:

```jsx
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](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/original-image-node-jimp.jpeg?resize=730%2C486&ssl=1)

Resized image:

![Resized Image of a Sofa, Coffee Table, and Pillows](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/resized-node-jimp.png?resize=150%2C150&ssl=1)

`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:

```jsx
crop( x, y, w, h)
```

Example:

```jsx
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](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/cropped-node-jimp.png?resize=150%2C150&ssl=1)

## 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:

```jsx
rotate( deg[, mode] );
```

Example:

```jsx
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](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/rotate-node-jimp.png?resize=730%2C730&ssl=1)

### Flip

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

Syntax:

```jsx
image.flip( horz, vert )
```

Example:

```jsx
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](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/flip-node-jimp.png?resize=730%2C486&ssl=1)

### Opacity

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

Syntax:

```jsx
opacity( f );
```

Example:

```jsx
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: ![](https://blog.logrocket.com/static/img/pixel.gif)

![Opaque Image of a Sofa, Coffee Table, and Pillows](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/opacity-node-jimp.png?resize=730%2C487&ssl=1)

## Applying image effects and filters

### Grayscale

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

Syntax:

```jsx
greyscale();
>
```

Example:

```jsx
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](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/grayscale-node-jimp.png?resize=730%2C486&ssl=1)

### 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:

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

Example:

```jsx
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](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/blur-node-jimp.png?resize=730%2C486&ssl=1)

## Image and text overlays

### Image overlay

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

Syntax:

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

Example:

```jsx
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](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/image-overlay-node-jimp.png?resize=730%2C486&ssl=1)

### 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:

```jsx
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](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/02/text-overlay-node-jimp.png?resize=730%2C486&ssl=1)

## 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](https://github.com/oliver-moran/jimp) and [npm](https://www.npmjs.com/package/jimp) 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.](https://www2.logrocket.com/signup-lr)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/jd2amkhuiynfjf3i33qk.png)

[LogRocket](https://www2.logrocket.com/signup-lr) 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.](https://www2.logrocket.com/signup-lr)
* * *

The post [Image processing with Node and Jimp](https://blog.logrocket.com/image-processing-with-node-and-jimp/) appeared first on [LogRocket Blog](https://blog.logrocket.com).