Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Optimize Images in the Cloud

Learn how to optimize images in the cloud with clear steps, practical context, and useful troubleshooting guidance.

Table of Contents

This updated guide examines How to Optimize Images in the Cloud and organizes the essential facts, background, and practical takeaways in clear American English.

Method 1of 2:

Using AWS S3 and Lambda

  1. How to Optimize Images in the Cloud — contextual image 1 Set up AWS S3. Get started with setting up your AWS S3 bucket if you haven't already created one. Amazon S3 lets you store any amount of data and up to 5GB for free. Check out the article on Upload to Amazon S3 to set up and configure your AWS S3 account. Once you are done with that, create two folders in your bucket, and name them original and resized. As the name suggests, the original directory stores the original image whereas resized directory stores the resized image.
  2. Write the optimization code. We are going to useasync,aws-sdk,gm, andpathlibs for the demo optimization code. You will need to install node and all the dependencies first and then copy the following code into imageResizer.js .
    // dependenciesvarasync=require('async');varAWS=require('aws-sdk');vargm=require('gm').subClass({imageMagick:true});// Enable ImageMagick integration.varutil=require('util');varpath=require('path');// constantsvarWEB_WIDTH_MAX=150;varWEB_HEIGHT_MAX=150;varimageResponse;// get reference to S3 clientvars3=newAWS.S3();exports.handler=function(event,context,callback){// Read options from the event.console.log("Reading options from event:n",util.inspect(event,{depth:5}));varsrcBucket=event.Records[0].s3.bucket.name;// Object key may have spaces or unicode non-ASCII characters.varsrcKey=decodeURIComponent(event.Records[0].s3.object.key.replace(/+/g," "));// var dstBucket = srcBucket + "-resized";varimageName=path.basename(srcKey);vardstBucket=srcBucket;varimageResponse;// Infer the image type.vartypeMatch=srcKey.match(/.([^.]*)$/);if(!typeMatch){callback("Could not determine the image type.");return;}varimageType=typeMatch[1];if(imageType.toUpperCase()!="jpg".toUpperCase()&&imageType.toUpperCase()!="png".toUpperCase()&&imageType.toUpperCase()!="jpeg".toUpperCase()){callback('Unsupported image type: ${imageType}');return;}functionuploadWebMax(response,buffer,next){// Stream the transformed image to a different S3 bucket.vardstKeyResized="resized/"+imageName;s3.putObject({Bucket:dstBucket,Key:dstKeyResized,Body:buffer,ContentType:response.ContentType},function(err,data){if(err){console.log(err,err.stack);}else{console.log('uploaded to web-max Successfully!!');next(null,response,buffer);}});}
  3. Configure AWS Lambda. Next, you need to login to the AWS console and select Lambda from the services. From the Lambda page, select the `create the lambda function` button.
  4. How to Optimize Images in the Cloud — contextual image 2 Create a Lambda function for optimizing images. You will be asked to select a blueprint. Click on Blank function.
    • Configure trigger. You will be asked to add a trigger that will invoke the lambda function. Choose S3 here.
    • Select the bucket that we created earlier. Set the event type to Object created (All) and the prefix to original/. Press next.
    • Choose a function name. Select zip for code entry and use the upload the zip that we created earlier. The alternate inline option can use if there aren't any dependencies.
  5. Set up the IAM Roles. Now, you will need to fill in the handler name and the IAM role for Lambda. In 'Lambda function handler and role' field, change the name of the handler to imageResizer.js. The name of the js file inside our zip and the handler needs to match. From the Roles tab, select the option custom role. You can define new roles and add a policy here.
  6. Done. From the final screen, press creation function button. Congratulations, you have successfully created a lambda function that optimizes an image and then moves it to the resized folder. You can POST new images to the original bucket and pull resized version of the image from the resized bucket.

Method 2of 2:

Using Cloudinary and Node.js

  1. How to Optimize Images in the Cloud — contextual image 3 Set up and configure your account. Similar to that of S3, Cloudinary has a free tier plan that you can use. Once you are logged in, make note of thecloud_name,api_key, and theapi_secret.
  2. Add the cloudinary library to your project. We will be creating a sample Node.js project to demonstrate how it works. Install node.js if you haven't already. Next, create a directory for this project and install the dependencies using npm.
    npm install cloudinary
  3. Configure the credentials. Import the dependencies into your node project and configure the credentials that you noted in step 1.
    cloudinary.config({cloud_name:'sample',api_key:'874837483274837',api_secret:'a676b67565c6767a6767d6767f676fe1'});
  4. Create an upload function. Write an upload function that makes an async request to the cloudinary server. We are going to use a static image, but for practical purposes, the upload function will be called on form submission. Alternatively, you can upload on the fly from the client-side by making an AJAX call. You can about AJAX file upload on their documentation page.
    functionupload(file,options,callback){cloudinary.v2.uploader.upload("/home/my_image.jpg",function(error,result){console.log(result)});
  5. Understand the response from the server. Cloudinary assigns a public id and a URL that you can use to reference the uploaded resource. Since the pubic_id is synonymous to the image name, you can set the public_name while uploading the image. Once you are done with the file upload, you will get a return object that looks like this:
    {public_id:'cr4mxeqx5zb8rlakpfkg',version:1372275963,signature:'63bfbca643baa9c86b7d2921d776628ac83a1b6e',width:864,height:576,format:'jpg',resource_type:'image',created_at:'2017-06-26T19:46:03Z',bytes:120253,type:'upload',url:'https://res.cloudinary.com/demo/image/upload/v1372275963/cr4mxeqx5zb8rlakpfkg.jpg',secure_url:'https://res.cloudinary.com/demo/image/upload/v1372275963/cr4mxeqx5zb8rlakpfkg.jpg'}
  6. Optimize the image: For optimizing the image, there are multiple ways that you can do this — using the URL or the cloudinary lib.
    • Optimizing the image using the URL. You can change the size, dimension, quality and many other properties of the image by sending a request to the actual image URL. The transformed images are created on demand and returned to your node server. Here is an example of image optimization in action:
      https://res.cloudinary.com/demo/image/upload/q_60/sample.jpg
    • Optimizing the image using the library method. Alternatively, you can use the library method to make the transformation. The first argument is the public_id of the image and a second parameter is an object that comprises of the optimization parameters.
      cloudinary.image("sample.jpg", { quality: 50 })
  7. That's it. You have a fully working on-the-fly image manipulation solution integrated into your node application.

FAQ

What is How to Optimize Images in the Cloud about?

It provides a structured overview of image, explains the main context, and highlights practical takeaways for readers.

Why does this topic matter?

Understanding the main concepts helps readers evaluate the issue, avoid common mistakes, and make better-informed decisions.

How should readers use this information?

Use the guidance as a practical starting point, confirm details that may have changed, and follow current product, safety, or security recommendations.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.