Resizing an Image with NodeJs<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Resizing an Image with NodeJs

Posted on: August 1, 2017

This is the second post about project of creating a search tool for local pictures. As mentioned in the first post, this tool needs to use a web service to get information about the picture. This mean we need to upload the image that Microsoft Cognitive Vision/Face service will analyze and return a JSON object with information about the picture. Like most service, there is some constraints in term of the minimum and maximum of the size of what you can upload. Also, even for us, we do not want to send a 25 megs picture when it is not necessary. This article discuss about how to resize picture before sending a request to the web service. This will not only allow to be withing the range of the acceptable values, but also speed up the upload.

I decide to take the arbitrary value of sending picture with the widest side of 640px. This produce in average a file 30kb which is tiny but still enough for the cognitive service to give very good result. This value may not be good if you are building something similar where people are far or if you are not using portrait pictures. In my case, the main subjects are always close range, hence very easy to get detail at that small resolution.

Resizing a file requires to use a third-party library. This is something easy to find with JavaScript and NPM has a library named "Sharp" that do it perfectly. The TypeScript definition file is also available, so we are in business!

1npm install --save sharp npm install --save-dev @types/sharp

Before anything, even if this project is for myself, I defined some configuration variables. Some rigor is required when it's cheap to do! The three first constant is the maximum size we want to output the image. I choose 640 pixel. The directory name is the constant of the folder where we will save the image we will send and where we will late save the JSON file with the analysed data. We save the resized image because on the website later, we will use this small image instead of the full resolution image. The website will be snappy and since we have the file, why not using this optimization for free. At 30kb for 2000 images, we only use 58 megs. The last constant is the glob pattern to get all underscore JPEG pictures. We will talk about glob very soon.

1const maxSize = 640;
2const directoryName = "metainfo";
3const pathImagesDirectory = path.join(imagesDirectory, "**/_*.+(jpg|JPG)");

The second pre-task is to find the images to resize. Again, this will require a third-party library to simplify our life. We could recursively navigate folders, but it would be nicer to have a singe glob pattern that handle it.

1npm install --save glob npm install --save-dev @types/glob

From there, we need to import the module. We will bring the path and fs module of NodeJs to be able to create proper path syntax and to save file on disk.

1import _ as g from "glob";
2import _ as path from "path";
3import _ as sharp from "sharp";
4import _ as fs from "fs";

The first function that we need to create is the one that return a list of string that represent the file to resize. This will be all our underscore aka best pictures. We want to be sure that we can re-run this function multiple times, thus we need to ignore the output folder where we will save resized images. This function returns the list in a promise fashion because the glob library is asynchronous. Here is the first version which call the module function "Glob" and add everything into an array while sending in the console the file for debugging purpose.

1function getImageToAnalyze(): Promise<string[]> {
2 const fullPathFiles: string[] = [];
3 const promise = new Promise<string[]>((resolve, reject) => {
4 const glob = new g.Glob(pathImagesDirectory, { ignore: "**/" + directoryName + "/**" } as g.IOptions, (err: Error, matches: string[]) => {
5 matches.forEach((file: string) => {
6 console.log(file); fullPathFiles.push(file);
7 });
8 resolve(fullPathFiles);
9 });
10 });
11 return promise;

This can be simplified by just returning the matches string array and returning the promise instead of using a variable. At the end, if you are not debugging you can use :

1function getImageToAnalyze(): Promise<string[]> {
2 return new Promise<string[]>((resolve, reject) => {
3 const glob = new g.Glob(
4 pathImagesDirectory,
5 { ignore: "**/" + directoryName + "/**" } as g.IOptions,
6 (err: Error, matches: string[]) => {
7 resolve(matches);
8 }
9 );
10 });

As mentioned, the quality of this code is average. In reality, some loves are missing around the error scenario. Right now, if something is wrong, the rejection promise bubble up.

At this point, we can call the method with :

1console.log("Step 1 : Getting images to analyze " + pathImagesDirectory);
2getImageToAnalyze().then((fullPathFiles: string[]) => {
3 console.log("Step 2 : Resize " + fullPathFiles.length + " files");
4 return resize(fullPathFiles);

The code inside the then is the one executed if the promise is resolved successfully. It will start resizing the list of pictures and pass this list into the function that we will create in an instant.

The resize function is not the one that will do the resize. It will call the function that does the resize only if the picture has not been yet resized. This is great if something happen to fail and you need to re-run. The resize function will check in the "metainfo" folder, where we output the resized picture and only resize this one if not present. In both case, this function return a promise. The type of the promise is a list of IImage.

1export interface IImage {
2 thumbnailPath: string;
3 originalFullPathImage: string;

This type allows to have the detail about the full path of the thumbnail "resized" picture and the original picture. When we have already resized, we just create an instance, when we do not have an image we create this one and then return a new instance. This method waits all resize to occur before resolving. This is the reason of the .all. We are doing so just to have a clear cut before moving to the next step and since we are launching multiple resizes in parallel, we are waiting to have them all done before analyzing.

1function resize(fullPathFiles: string[]): Promise<IImage[]> {
2 const listPromises: Array<Promise<IImage>> = [];
3 const promise = new Promise<IImage[]>((resolve, reject) => {
4 for (const imagePathFile of fullPathFiles) {
5 const thumb = getThumbnailPathAndFileName(imagePathFile);
6 if (fs.existsSync(thumb)) {
7 listPromises.push(
8 Promise.resolve({
9 thumbnailPath: thumb,
10 originalFullPathImage: imagePathFile,
11 } as IImage)
12 );
13 } else {
14 listPromises.push(resizeImage(imagePathFile));
15 }
16 }
17 Promise.all(listPromises).then((value: IImage[]) => resolve(value));
18 });
19 return promise;

This function use a function to get the thumbnail path to lookup if it's been already created or not. This function call another one too, and both of these methods are having the same goal of providing a path. The first one, the getThumbnailPathAndFileName get the original full quality picture path and return the full image path of where the resized thumbnail is stored. The second one is a function that will be resused in some occasion and it gives the metainfo directory. This is where the resized picture are stored, but also the JSON file with the analytic data are saved.

1function getThumbnailPathAndFileName(imageFullPath: string): string {
2 const dir = getMetainfoDirectoryPath(imageFullPath);
3 const imageFilename = path.parse(imageFullPath);
4 const thumbnail = path.join(dir, imageFilename.base);
5 return thumbnail;
8function getMetainfoDirectoryPath(imageFullPath: string): string {
9 const onlyPath = path.dirname(imageFullPath);
10 const imageFilename = path.parse(imageFullPath);
11 const thumbnail = path.join(onlyPath, "/" + directoryName + "/");
12 return thumbnail;

The last method is the actual resize logic. The first line of the method create a "sharp" object for the desired picture. Then we invoke the "metadata" method that will give us access to the image information. We need this to get the actual width and height and do some computation to get the wider side and find the ratio of resizing. Once we know the height and the width of the thumbnail we need to create the destination folder before saving. Finally, we need to call the "resize" method with the height and width calculated. The "webp" method is the one that generate the image. From there, we could generate a buffered image and use a stream to handle it in memory or to store it on disk like we will do with the method "toFile". This return a promise that we use to generate and return the IImage.

1function resizeImage(imageToProceed: string): Promise<IImage> {
2 const sharpFile = sharp(imageToProceed);
3 return sharpFile.metadata().then(
4 (metadata: sharp.Metadata) => {
5 const actualWidth = metadata.width;
6 const actualHeight = metadata.height;
7 let ratio = 1;
8 if (actualWidth > actualHeight) {
9 ratio = actualWidth / maxSize;
10 } else {
11 ratio = actualHeight / maxSize;
12 }
13 const newHeight = Math.round(actualHeight / ratio);
14 const newWidth = Math.round(actualWidth / ratio);
15 const thumbnailPath = getThumbnailPathAndFileName(imageToProceed); // Create directory thumbnail first
16 const dir = getMetainfoDirectoryPath(imageToProceed);
17 if (!fs.existsSync(dir)) {
18 fs.mkdirSync(dir);
19 }
21 return sharpFile
22 .resize(newWidth, newHeight)
23 .webp()
24 .toFile(thumbnailPath)
25 .then((image: sharp.OutputInfo) => {
26 return {
27 thumbnailPath: thumbnailPath,
28 originalFullPathImage: imageToProceed,
29 } as IImage;
30 });
31 },
32 (reason: any) => {
33 console.error(reason);
34 }
35 );

This conclude the resize part of the project. It's not as straight forward as it may seem, but noting is space rocket science either. This code can be optimized to start resizing without having analyzed if all the image are present or not. Some refactoring could be done around the ratio logic within the promise callback of sharp's metadata method. We could also optimize the write to remain in memory and hence having not to reload the thumbnail from the disk but working the on the memory buffer. The last optimization wasn't done because I wanted every step to be re-executed what ever the state in which they were stopped. I didn't wanted to bring more logic to reload in memory if already generated. That said, it could be done. The full project is available on GitHub :