I had a situation where I had no backend server to handle the crop and resizing of an image. I know of a few cloud services which could do this easily however they come with a cost. So I thought to implement the solution within the browser itself. Before we proceed, let we warn you that this might not be an optimal solution for a page with a lot of images and which might require the use of web worker to offload the task to worker threads.
To load JIMP in browser we are going to use unpkg CDN. If you are not familiar with unpkg or how to load any npm package in browser, please refer to tutorial, How to load any npm module in browser
To load JIMP using unkpg, we create a script tag
Next, we create simple markup where original and cropped images will be loaded
and little bit of styling :-)
Now coming to the interesting stuff let’s play with JIMP to crop the image.
First, we need to load the image with
Jimp.read() method that returns a promise.
Jimp object. If we log the
image variable on the console, returned by
Jimp.read() method we should see output something similar to below image
Jimp prototype chain contains a method
crop which we will use in the next step to crop the image.
Once we have Jimp object, we can pass the
h as arguments to define crop region inside
image.crop() method which would return
Once the Promise to crop an image is resolved, we can use
then() method to get the
base64 image using the method
getBase64() method accepts,
callback as first and second arguments respectively.
In the callback arrow function, we are setting a source of second image element that is stored in variable
This step is optional as I want to demonstrate how we can compare the size of the original with cropped one.
To display the dimension of the image, I used
for loop to create a
span element. The
span element will be displayed on top of the existing images on the top left corner with the respective image size as the text.
As we can see the size of original image was
640x400 whereas the size of new image is