Image Compression Functionality

CODE: 

        var ext = fileNames.substr(fileNames.lastIndexOf(‘.’) + 1);  
        if(ext == ‘jpeg’ || ext == ‘png’ || ext == ‘jpg’ || ext == ‘JPEG’ || ext == ‘PNG’ || ext == ‘JPG’)  {
          INPUT_path_to_your_images = global.paths.path+’public/uploads/’+obj+’/’+fileNames;
          OUTPUT_path = global.paths.path+’public/uploads/’+obj+’/compressed/’+fileNames;
       
          sizeOf(INPUT_path_to_your_images, function (err, dimensions) {
            if(dimensions.height > 600){
              Jimp.read(INPUT_path_to_your_images, function (err, lenna) {
                if (err) throw err;
                lenna.resize(600, Jimp.AUTO)            // resize
                     .quality(60)                 // set JPEG quality // set greyscale
                     .write(OUTPUT_path); // save
                     cb(null);
              });
            } else {
              Jimp.read(INPUT_path_to_your_images, function (err, lenna) {
                if (err) throw err;
                lenna.write(OUTPUT_path);             // save    // set JPEG quality // set greyscale
                cb(null);
              });
            }
          });
        } else {
          cb(null);
        }

Explanation: 

1. Every image will pass through the compression function on multer (which is used to upload image)

        if(ext == ‘jpeg’ || ext == ‘png’ || ext == ‘jpg’ || ext == ‘JPEG’ || ext == ‘PNG’ || ext == ‘JPG’)  {

2. If we have the height above 600px we would reduce the height and width and do the compression which will reduce the size = 600px. So it would be ideal for all our web screens to be viewed properly.

if(dimensions.height > 600){

               lenna.resize(600, Jimp.AUTO)            // resize
                     .quality(60)                 // set JPEG quality // set greyscale
                     .write(OUTPUT_path); // save

3. If the original height is below 600 px we would leave it as same and does not compress and the image size would already be less and if we make the height as 600 the image would be stretched.

 else {
                lenna.write(OUTPUT_path);   

4. After compression we would make the same copy of the image into the compressed folder. While viewing on the search or other outer page we would show the compressed images. 

          INPUT_path_to_your_images = global.paths.path+’public/uploads/’+obj+’/’+fileNames;
          OUTPUT_path = global.paths.path+’public/uploads/’+obj+’/compressed/’+fileNames;

5. In Images gallery or in inner pages where the full image is shown we would show the original image without compression so user can see the details of the images.

This would make images loading on search and other pages to be fast as loading of images would be faster if the size is reduced.

Thus we have implemented Compression in our softwares