How to display an image from Amazon S3 on your website?

Most people use Amazon S3 to store images so that they can fetch them whenever required to display on their website. In this blog, I am going to show you the ways this can be done.

In case you are someone new to AWS then take a look at this article to know what AWS is and what solution they offer.

Decide S3 accessibility level

  • Decide whether the object needs to be public or private in S3.
  • The easiest solution will be to make the object public (read-only) in S3.
  • Just directly refer to the S3 URL in the img tag. For example
<img src="https://my-bucket-name.s3.ap-south-1.amazonaws.com/IMG_6387.PNG" alt="image.com">
  • The S3 URL can be taken as shown below.
  • If you cannot afford to keep your object public there are few workarounds that you can follow.

Use the lambda function to access the private S3 image

Create a lambda function with necessary permissions to access the private S3 image and return the base64 response from the function.

const AWS = require('aws-sdk');
//*/ get reference to S3 client 
var s3 = new AWS.S3();
exports.handler = (event, context, callback) => {
    var params = {
  "Bucket": "bucket-name",
  "Key": "object-name"  
    };
    s3.getObject(params, function(err, data){
       if(err) {
           callback(err, null);
       } else {
           let image = new Buffer(data.Body).toString('base64');
           image = "data:"+data.ContentType+";base64,"+image;
           let response = {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": "*",
            'Content-Type': data.ContentType
        },
        "body":image,
        "isBase64Encoded": true
    };
           callback(null, response);
    }
    });
    
};

Make sure to enable the function URL from the lambda function or create a REST API with Amazon API Gateway and invoke this function.

Use Presigned URL

The presigned URL allows you to access the image for a specific period of time. A presigned URL can be created by the following code

Python

import boto3

s3_client = boto3.client(
    's3',
    region_name='your_region_name',
    aws_access_key_id='your_aws_access_key_id',
    aws_secret_access_key='your_aws_access_key_id',
)

# Just specify folder_name:
url = s3_client.generate_presigned_url(
    ClientMethod='put_object',
    Params={'Bucket': 'your_bucket_name', 'Key': 'folder_name/file_name.jpg',},
    ExpiresIn=60,
)

Php

//Get an instance of S3 Client. This is one one to do it:
$s3Client = new S3Client([
    'version'     => 'latest',
    'region'      => 'us-west-2', //Region of the bucket
    'credentials' => array(
        'key' => 'YOUR-ACCOUNT-KEY',
        'secret'  => 'YOUR-ACCOUNT-SECRET',
    )
]);

//Get a command to GetObject
$cmd = $s3Client->getCommand('GetObject', [
    'Bucket' => 'YOUR-BUCKET-NAME',
    'Key'    => 'YOUR-FILE-KEY'
]);

//The period of availability
$request = $s3Client->createPresignedRequest($cmd, '+10 minutes');

//Get the pre-signed URL
$signedUrl = (string) $request->getUri();

Happy Programming!!

Leave a Comment