How to Convert all Images to Base64 and Update Records in Retool

Hello everyone,

I am currently working on an application in Retool where I need to convert stored images to base64 and update the records in my database. Here are the details of my setup and what I have tried so far:
. Context:

  • I have a table DB2_Table_Batisses that contains columns for image codes (e.g., annexe1_photo, annexe2_photo, etc.).
  • I want to convert these codes to base64 URLs and store them in corresponding columns (Annexe1_base64, Annexe2_base64, etc.).
const myImageUrl = 'https://i.pinimg.com/736x/ba/92/7f/ba927ff34cd961ce2c184d47e8ead9f6.jpg";

/**
 * Fetches an image from URL and encodes it into a base64 string
 * Adapted from this thread: https://community.cloudflare.com/t/convert-request-body-to-base64-encoded-string-solved/99341/5
 * @param {string} url
 * @returns {Promise<string>}
 */
async function imageUrlToBase64(url) {
  let string = "";
  const response = await fetch(url);
  const buffer = await response.arrayBuffer();
  (new Uint8Array(buffer)).forEach(
    (byte) => { string += String.fromCharCode(byte) }
  )
  return btoa(string);
}

// usage:
const imageBase64_async = await imageUrlToBase64(myImageUrl);

// usage without await
imageUrlToBase64(myImageUrl).then((ret) => {
  console.log("Base64String: ", ret);
});

source

you could also use fetch with FileReader

const imageUrlToBase64 = async url => {
  const response = await fetch(url);
  const blob = await response.blob();
  return new Promise((onSuccess, onError) => {
    try {
      const reader = new FileReader() ;
      reader.onload = function(){ onSuccess(this.result) } ;
      reader.readAsDataURL(blob) ;
    } catch(e) {
      onError(e);
    }
  });
};

// usage
const myImageUrl = 'https://i.pinimg.com/736x/ba/92/7f/ba927ff34cd961ce2c184d47e8ead9f6.jpg";
const base64 = await imageUrlToBase64(myImageUrl);
1 Like

Hii @Said

async function imageUrlToBase64(url) {
  // Fetch the image data
  const response = await fetch(url);
  const blob = await response.blob();

  // Create a FileReader to read the Blob data
  const reader = new FileReader();
  return new Promise((resolve, reject) => {
    reader.onloadend = () => {
      const base64String = reader.result.split(',')[1];
      resolve(base64String);
    };
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
}

// Usage example
imageUrlToBase64('https://example.com/image.jpg').then(base64String => {
  console.log('Base64 String:', base64String);
});

  1. Fetch the Image: The fetch API is used to get the image data as a Blob.
  2. Read the Blob: The FileReader reads the Blob data and converts it to a Data URL.
  3. Extract Base64 String: The Data URL contains the Base64 string, which is extracted by splitting the string and taking the part after the comma.
1 Like