[Solved]-Convert an Image Url Into Base64 Data URL Using JavaScript With CORS

[Solved]-Convert an Image Url Into Base64 Data URL Using JavaScript With CORS

Right Now, I’m working on a Web App project and My Team loader assigns a task to me. Use base64 encoded images in our Web Application to optimize the load time very tiny images and we also need to hide the URL of the images. 
So let’s start, In this post, I will discuss, how you can convert an image URL into base64.
It is very simple to load a base64 image onto a canvas. The method toDataURL() of the canvas is very important for this process and I will explain to you, how you can use it.
I want to convert an image URL into base64 because I want to hide the image URL from the user because of the security thread.
So that I have created a JavaScript function that converts image URL to base64 but when I run my application I get the error “Access to Image at from origin has been blocked by CORS policy: No ‘Access-Control-Allow-Origin‘”(For More). Because JavaScript code running on a website cannot access resources from other websites. JavaScript can access website resources from that same website.
This is implemented in all major browsers.I searched may tutorial and found a solution just add this URL https://crossorigin.me/ before your image URL.
 
Like this
Now it will work perfectly.
As we know that Base64 encoded files are larger than the original files. So that base64 encoded images are best for the small images not for large files. 

 

<html>
<head>
    <title>DotNetPeTips</title>
    
</head>
<body>
    <fieldset>
        <legend>Base64 Image</legend>
        <input id="Button" onclick="encodeImage("https://nodejs.org/static/legacy/images/logo-light.png")" type="button" value="LoadImage" />
        <br />
        <img id="Image1" />
    </fieldset>
<script type="text/javascript">
          function encodeImage(src, callback) {
              var canvas = document.createElement('canvas'),
                  ctx = canvas.getContext('2d'),
                  img = document.getElementById("Image1");
              img.onload = function () {
                  canvas.width = img.width;
                  canvas.height = img.height;
                  ctx.drawImage(img, 0, 0, img.width, img.height);
                  callback(canvas.toDataURL());
              }
              img.src = src;
          }
    </script>
</body>
</html>

 

In this post we covered the following Topic:

  • Covert Image url to Base64
  • How to get base64 encoded data from html image
  • Convert Image to Data URI
  • JavaScript – CONVERT Image url to Base64
  • How to Get and Set a Base64 Image on Canvas using toDataURL

Approach:2 Using FileReader

We can Load the image as blob using XMLHttpRequest and then use the FileReader API to convert it to a base64 Data Url:
 
<!DOCTYPE html>
<html>
<head>
    <title>DotNetPeTips</title>
    <meta charset="utf-8" />
</head>
<body>
    <fieldset>
        <legend>Base64 Image</legend>
        <img id="Image1" />
    </fieldset>
    <script type="text/javascript">
        const ImagetoDataURL = url => fetch(url)
                          .then(response => response.blob())
                          .then(blob => new Promise((resolve, reject) => {
                              const reader = new FileReader()
                              reader.onloadend = () => resolve(reader.result)
                              reader.onerror = reject
                              reader.readAsDataURL(blob)
                          }))


        ImagetoDataURL('https://www.gravatar.com/avatar/')
          .then(dataUrl => {
              console.log('DataURL:', dataUrl)
              document.getElementById("Image1").src = dataUrl;
          })
    </script>
</body>
</html>

Ashok Patel

I'm an electronic engineer working in a multinational company,having good experience on Electronics and electrical engineers design and oversee production of electronic equipment such as radios, televisions, computers, washing machines and telecommunication systems.I like to do RND and Research.I also have hands on experience graphic design software and in web designing having great command on ASP.NET, HTML5, JavaScript, T-SQL, JQuery.

Add comment

Donate for Corona Victim

Corona Virus Relief Fund

Your Header Sidebar area is currently empty. Hurry up and add some widgets.