Process Images the right way | SharpJS

A complete guide on Sharp.js, a light and easy Javascript Library used for Image Processing

In this article, we're going to discuss how to solve a problem. A problem that we face in our day-to-day lives, as developers. The problem is processing heavy images.

As you know, images are a big integral part of any modern user-friendly application today. Let's take an example of any social media platform, or an e-commerce website, or pretty much any other website, they all make use of images in some way or another. In some platforms, the users want to crop, update, or apply filters onto their pictures, and on other platforms, such as e-commerce platforms, merchants want to enhance the images of their products so that they sell more and more products. Besides, the most tricky part is to deal with large images, what's more, frustrating is to store those heavy images into databases, and, on a bad internet connection they can take forever to load.

Now, don’t worry, I'm not only here with the problem but I bring the solution as well. There's a way we can make our images load faster, even with higher quality while also making them more user friendly. As you might have guessed by now, the solution is the SharpJS library used with Node.js applications.

The typical use case for this high speed Node.js module is to convert large images in common formats to smaller, web-friendly JPEG, PNG and WebP images of varying dimensions.

- According to the Official Documentation for SharpJS

1) Pre-Requisites

There is just one requirement, that we need to cater to before we can start using this library, which is, you should have NodeJs v10 or newer. That’s it!

2) Installation and Import

  • To install using npm:

npm install sharp
  • To install using yarn:

yarn add sharp

3) Using SharpJS

Prior to start using this library we need to require it, just like pretty much any other Javascript library.

const sharp = require("sharp");

4) Examples

Next, let's look at some examples of how we can use this library.

Example 1: Resize / Crop Image

sharp("Input_Image.jpg")
  .resize({ width: 250, height: 350 })
  .toFile("Output.jpg");

The toFile( ) method writes output image data to a file. In this case, the resized image will be saved in an output file named “Output” of type JPG.

Example 2: Obtaining Image Greyscale

 sharp("Input_Image.jpg")
  .greyscale()  //.grayscale()
  .toFile("Output.jpg");

The greyscale( ) method (Alternative spelling, grayscale. You can use either). Converts the input image to 8-bit greyscale; 256 shades of grey.

Example 3: Obtaining Image Negative

 sharp("Input_Image.jpg")
  .negate()
  .toFile("Output.jpg");

This produces the "negative" of the image.

Example 4: Blur Image

 sharp("Input_Image.jpg")
  .blur()
  .toFile("Output.jpg");

When the blur( ) method is used without parameters, it performs a fast, mild blur of the output image. However, you can also provide a sigma value for it to perform a slower, more accurate Gaussian blur. Sigma value can range between 0.3 and 1000.

Example 5: Rotate Image

sharp("Input_Image.jpg")
  .rotate(180)
  .toFile("Output.jpg");

Rotates the image to a positive 180 degrees rotation.

Example 6: Flip Image

sharp("Input_Image.jpg")
  .flip()
  .toFile("Output.jpg");

Flips the image about the vertical Y-axis.

Example 7: Flop Image

sharp("Input_Image.jpg")
  .flop()
  .toFile("Output.jpg");

Flops the image about the horizontal X-axis.

Example 8: Change Image Format

sharp("Input_Image.jpg") 
  .toFormat("png")
  .toFile("Output.png");

Transforms the input image into a new format provided as an argument to the toFormat( ) method.

Example 9: Enhance Image Quality

sharp("Input_Image.jpg")
  .toFormat("png")
  .png({ quality: 100 })
  .toFile("Output.png");

The quality of the image can be set anywhere between 1 to 100. Needless to say, the higher the value, the better the quality.

Example 10: Storing Image into the Database

  
sharp("Input_Image.jpg")
  .resize({ width: 500, height: 450 })
  .toFormat("png")
  .png({ quality: 100 })
  .toFile("Output.png")
  .then(() => {
    //Here, you can either store the image to the database or     
//send it to the frontend client(React, Vue, Angular, etc.)
    
  console.log('Please Like Comment and Subscribe!!');

  })
  .catch((err) => console.warn(err)); // print error(if any) on the console

Now, here, we want to resize the image give it a width of 500 pixels and a height of 450 pixels, then, we want to transform it into the PNG format, next we set the quality of the output image to be 100, and the output image is saved as “Output.png”. After all the previous filters have been applied to the image, the .then( ) block will be executed which takes a callback function, where you can perform any operation with the output image.

In addition to promises, SharpJS also works with callbacks and async await.

Example 11: Work with GIFs

sharp('inputGIF.gif', { animated: true })
  .toFile('Output.webp');

Convert a gif into a WEBP format, while still retaining the animations.

So, that’s it about this useful Javascript library. I hope the information provided in this article provides value to you and helps you simplify and optimize the future image processing tasks on your web app.

Helpful Resources: