How to Optimize Images in the Cloud
Method 1 of 2:
Using AWS S3 and Lambda
- 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.
- Write the optimization code. We are going to use
async
,aws-sdk
,gm
, andpath
libs 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.// dependencies var async = require('async'); var AWS = require('aws-sdk'); var gm = require('gm') .subClass({ imageMagick: true }); // Enable ImageMagick integration. var util = require('util'); var path = require('path'); // constants var WEB_WIDTH_MAX = 150; var WEB_HEIGHT_MAX = 150; var imageResponse; // get reference to S3 client var s3 = new AWS.S3(); exports.handler = function(event, context, callback) { // Read options from the event. console.log("Reading options from event:n", util.inspect(event, {depth: 5})); var srcBucket = event.Records[0].s3.bucket.name; // Object key may have spaces or unicode non-ASCII characters. var srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/+/g, " ")); // var dstBucket = srcBucket + "-resized"; var imageName=path.basename(srcKey); var dstBucket = srcBucket; var imageResponse ; // Infer the image type. var typeMatch = srcKey.match(/.([^.]*)$/); if (!typeMatch) { callback("Could not determine the image type."); return; } var imageType = typeMatch[1]; if (imageType.toUpperCase() != "jpg".toUpperCase() && imageType.toUpperCase() != "png".toUpperCase() && imageType.toUpperCase() != "jpeg".toUpperCase()) { callback('Unsupported image type: ${imageType}'); return; } function uploadWebMax(response, buffer, next) { // Stream the transformed image to a different S3 bucket. var dstKeyResized = "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); } }); }
- 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.
- 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.
- 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.
- 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 2 of 2:
Using Cloudinary and Node.js
- 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 the
cloud_name
,api_key
, and theapi_secret
. - 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
- 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' });
- 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 read more about AJAX file upload on their documentation page.
function upload(file, options, callback) { cloudinary.v2.uploader.upload("/home/my_image.jpg", function(error, result) {console.log(result)});
- 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' }
- 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 })
- 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:
- That's it. You have a fully working on-the-fly image manipulation solution integrated into your node application.
4.5 ★ | 6 Vote
You should read it
- How to Upload an Animation in a Signature
- Size, size of the standard image for Facebook Fanpage is how much?
- Facebook on mobile will automatically optimize images when you upload
- How to upload and upload Videos to YouTube on Android?
- Instructions for fixing errors do not download photos from iPhone to Facebook
- How to upload HD photos to Facebook on iPhone / iPad?
- How to Upload, Download Videos to YouTube on iPhone?
- Upload videos to YouTube, how to upload videos to YouTube from the fastest computer
May be interested
- Learn to use lesson computer 14 - Learn about cloud storagein the process of using computers or the internet, there have been many times you have heard of terms such as cloud, cloud computing or cloud memory, cloud storage. but what exactly is cloud?
- Share experience in selecting and using cloud services effectivelycurrent cloud services appear quite a lot, so we have quite a few options to use in normal life as well as for work. however, how much should one choose, how should they be coordinated so that the services cloud really serves can best be for us?
- AWS and Azure dominate the cloud world, above all, no one winsbusinesses need to be sure not to rely on a single provider by focusing on demand before thinking about the ecosystem.
- Learn about Public Cloud, Private Cloud and Hybrid Cloudthere are many different ways to deploy and exploit cloud computing resources.
- Going to the cloud: The inevitable path of transforming numbers 4.0cloud computing is now not only a way to streamline business processes, but it is also a major difference that creates a unique competitive advantage. cloud technology has become an integral part of businesses in the ever-changing market cycle.
- How to use AnyTrans for Cloud to manage cloud servicesanytrans for cloud is a website that manages cloud storage services, such as google drive, onedrive, dropbox, ... on the same interface.
- What is Google Cloud Shell? What's remarkable about Cloud Shell?google cloud shell is an online development and operations environment that you can access anywhere via a web browser. cloud shell is a free service provided by google.
- How to optimize RAM to use Chrome on a Laptopthe fact that chrome on a laptop consumes ram is something that a lot of users feel dissatisfied with this web browser, the more tabs that are enabled, the higher the ram consumption of chrome is.
- Google Cloud Outage, Major Platforms Affectedgoogle cloud platform (gcp) suddenly encountered a prolonged problem, causing a series of popular applications and websites such as openai, discord, snapchat, shopify... to be inaccessible.
- [WP] How to automatically upload photos and videos to OneDriveonedrive is a great cloud storage tool that microsoft equips windows phone 8.1 operating system. backing up data (here photos and videos / clips) in the phone to the cloud is always encouraged by many experts. there are many reasons for you to save your images and videos to the cloud.