Search code examples
javascriptbase64cloudinary

How to turn cloudinary image to base64 img synchronously?


Pretty much what the post says. I don't want to use an async option and can't seem to find any out of the box cloudinary transformation that will do something like cloudinaryImg/transform_toBase64,w_20,h_20/123.jpg (this is an example). This also needs to be on the front end.

Also most of the javascript options seem to only do async.


Solution

  • You can generate the base64 of the image using its URL. Here are some resources -

    How can I convert an image into Base64 string using JavaScript?

    https://base64.guru/developers/javascript/examples/convert-image

    Here is a simple example influenced by the one given here -

    
    var url = 'https://res.cloudinary.com/demo/image/upload/sample.jpg';
    
    var xhr = new XMLHttpRequest();
    xhr.onload = function () {
      // Create a Uint8Array from ArrayBuffer
      var codes = new Uint8Array(xhr.response);
    
      // Get binary string from UTF-16 code units
      var bin = String.fromCharCode.apply(null, codes);
    
      // Convert binary to Base64
      var b64 = btoa(bin);
      console.log(b64); 
    };
    
    // Send HTTP request and fetch file as ArrayBuffer
    xhr.open('GET', url);
    xhr.responseType = 'arraybuffer';
    xhr.send();