Skip to content

read image from s3 as base64

0

Hi team,

I’m working with Node.js and TypeScript for my Lambda function, and I need to convert an image (e.g., image.jpg) retrieved from an S3 bucket into a base64-encoded string.

Here’s what I’ve tried so far:

  • Using transformToString method:

const base64ImageString = await imageObjectBody.transformToString("base64");

  • Reading the image content as a string and then encoding it:
const imageContent = await imageObjectBody.transformToString();
const base64ImageString = Buffer.from(imageContent).toString("base64");

However, neither approach seems to produce a valid base64 string, as converting this string back to an image using an online tool does not return the original image.

Could you please advise on the correct method to convert a JPEG or PNG image read from an S3 bucket into a base64-encoded string?

Thanks!

2 Answers
0
Accepted Answer

Hello.

I'm not very good at JavaScript, but I created some sample code.
I was able to encode the image in S3 to Base64 using the code below.
The code below can get the image "client.drawio.png" from the S3 bucket using "GetObjectCommand" and convert it to base64.
https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectCommand/
The image is converted to base64 in the "const base64Image = buffer.toString('base64');" part.

import {
  S3Client,
  GetObjectCommand
} from '@aws-sdk/client-s3'
const s3 = new S3Client({
  region: 'ap-northeast-1'
})

export const handler = async (event) => {
  // TODO implement
 const response = await s3.send(
      new GetObjectCommand({
        Bucket: 'kobayashi-lambda',
        Key: 'client.drawio.png'
      })
 );
 const chunks = [];
 for await (let chunk of response.Body) {
    chunks.push(chunk);
 }
 const buffer = Buffer.concat(chunks);
 const base64Image = buffer.toString('base64');
 console.log(base64Image);
};
EXPERT
answered a year ago
  • thanks for your answer, finally this : const base64ImageString = await imageObjectBody.transformToString("base64"); workout for me

0

Hi,

This article proposes you 3 different methods to do this conversion: https://pqina.nl/blog/convert-an-image-to-a-base64-string-with-javascript/

Best,

Didier

EXPERT
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.