What is resizing an image on-the-fly and How to do it?

What is resizing an image on-the-fly and How to do it?

April 10, 2022

Resizing an image on-the-fly refers to the process of changing the dimensions of an image without saving a new copy. This technique is useful when you need to display images in different sizes, for example, in a responsive web design or in a mobile application. In this article, we will explore how to resize an image on-the-fly using the JavaScript library, Sharp.

Sharp is a high-performance image processing library that allows you to manipulate images in real-time. It offers a wide range of features, including resizing, cropping, and converting images to different formats. It is well-suited for use in serverless environments, such as AWS Lambda or Google Cloud Functions.

Here's how to resize an image on-the-fly using Sharp:

  1. Install Sharp:
    • Open a terminal window and run the following command to install Sharp:
npm install sharp
  1. Load the Image:
    • Create a new JavaScript file and require the Sharp library:
const sharp = require('sharp');
- Load the image into memory by passing the image file path to the sharp() function:
const image = sharp('path/to/image.jpg');
  1. Resize the Image:
    • Call the resize() method on the image object to specify the new dimensions:
const resizedImage = image.resize({ width: 200, height: 200 });
- The resize() method accepts an object that contains the desired width and height of the image. If only one dimension is specified, the other dimension will be automatically calculated to maintain the aspect ratio of the original image.

4. Get the Resized Image: - Use the toBuffer() method to get the resized image as a binary buffer:

resizedImage.toBuffer().then((data) => {
    // Do something with the resized image data
});
  • The toBuffer() method returns a Promise that resolves with the binary data of the resized image. You can use this data to display the image on a web page, save it to a file, or perform other operations.

Here's how to resize an image on-the-fly using Sharp with AWS Lambda and AWS API

To resize an image on-the-fly using AWS API Gateway and AWS Lambda, you need to create an API endpoint that invokes a Lambda function. The Lambda function will be responsible for reading the original image, resizing it to the desired dimensions, and returning the resized image to the API endpoint. Here are the steps to set it up:

  1. Create a Lambda Function:
    • Log in to your AWS account, go to the AWS Lambda service, and create a new function.
    • Choose the "Author from scratch" option, give your function a name, select "Node.js" as the runtime, and create a new role for the function with basic execution permissions.
    • In the function code editor, paste the following code, which uses the sharp library to resize the image:
const sharp = require('sharp');

exports.handler = async (event) => {
    const image = Buffer.from(event.body, 'base64');
    const width = parseInt(event.queryStringParameters.width, 10);
    const height = parseInt(event.queryStringParameters.height, 10);

    const resizedImage = await sharp(image)
        .resize(width, height)
        .toBuffer();

    return {
        statusCode: 200,
        headers: {
            'Content-Type': 'image/jpeg',
            'Content-Length': resizedImage.length
        },
        body: resizedImage.toString('base64'),
        isBase64Encoded: true
    };
};
  1. Create an API Gateway:
    • Log in to your AWS account, go to the AWS API Gateway service, and create a new REST API.
    • Choose the "REST API" option and give your API a name.
    • Create a new resource and add a new POST method to it.
    • Connect the method to your Lambda function and enable CORS.
    • Deploy the API to a new stage.
  2. Test the API:
    • Copy the URL for the deployed API and paste it into a new browser window.
    • Add the width and height query parameters to specify the desired dimensions for the resized image.
    • Attach an image file to the body of the request and send it.
    • If everything is set up correctly, you should receive a response with the resized image.

That's it! With just a few lines of code, you can resize an image on-the-fly using Sharp. This library provides a powerful and flexible solution for resizing images in real-time, making it a great choice for applications that need to display images in different sizes.

In conclusion, resizing an image on-the-fly is a useful technique for adjusting the dimensions of an image without saving a new copy. Sharp is a powerful image processing library that makes it easy to resize images in real-time. Whether you're building a responsive web design or a mobile application, Sharp is a great choice for your image resizing needs.

Ready to try us out?

Have questions? Not sure what you need or where to start? We’re here for you.

Let's Talk