Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

jQuery Project to Encode Remote Image URL to Base64 Using FileReader & Canvas in Browser

Posted on December 6, 2022

 

 

Welcome folks today in this blog post we will be encoding the given url of image to base64 data url using filereader and canvas in jquery. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Remote URL Image to Base64</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css">
</head>
 
<body>
    <form class="form-horizontal" id="img2b64">
        <h2>Input</h2>
        <div class="form-group">
            <label class="col-sm-2 control-label">Convert via:</label>
            <div class="col-sm-10">
                <select class="form-control" name="convertType">
                    <option value="Canvas" selected>Canvas</option>
                    <option value="FileReader">FileReader</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label">URL:</label>
            <div class="col-sm-10">
                <input type="url" name="url" class="form-control" placeholder="Insert an IMAGE-URL"
                    value="http://upload.wikimedia.org/wikipedia/commons/4/4a/Logo_2013_Google.png" required />
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" class="btn btn-default">
            </div>
        </div>
    </form>
 
    <div class="output form-horizontal" style="display: none">
        <hr>
        <h2>Output</h2>
        <div>
            <strong class="col-sm-2 text-right">Converted via:</strong>
            <div class="col-sm-10">
                <span class="convertType"></span>
            </div>
        </div>
        <div>
            <strong class="col-sm-2 text-right">Size:</strong>
            <div class="col-sm-10">
                <span class="size"></span>
            </div>
        </div>
        <div>
            <strong class="col-sm-2 text-right">Text:</strong>
            <div class="col-sm-10">
                <textarea class="form-control textbox"></textarea>
            </div>
        </div>
        <div>
            <strong class="col-sm-2 text-right">Link:</strong>
            <div class="col-sm-10">
                <a href="#" class="link"></a>
            </div>
        </div>
        <div>
            <strong class="col-sm-2 text-right">Image:</strong>
            <div class="col-sm-10">
                <img class="img">
            </div>
        </div>
    </div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</html>

 

 

As you can see we are including the bootstrap and jquery cdn for this web app. And inside the html we have the simple select list where we select which approach should be used to convert the image to base64 data url either filereader and canvas And after that we have the input element where the user can write the url of the image to convert the image to base64 dataurl.

 

 

 

 

As you can see we have the submit button to call the method to convert the image to base64. Now we need to define the javascript code which is needed for this task

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$('#img2b64').submit(function(event) {
  var imageUrl = $(this).find('[name=url]').val();
  var convertType = $(this).find('[name=convertType]').val();
  var convertFunction = convertType === 'FileReader' ?
    convertFileToDataURLviaFileReader :
    convertImgToDataURLviaCanvas;
 
  convertFunction(imageUrl, function(base64Img) {
    $('.output')
      .find('.textbox')
      .val(base64Img)
      .end()
      .find('.link')
      .attr('href', base64Img)
      .text(base64Img)
      .end()
      .find('.img')
      .attr('src', base64Img)
      .end()
      .find('.size')
      .text(base64Img.length)
      .end()
      .find('.convertType')
      .text(convertType)
      .end()
      .show()
  });
 
  event.preventDefault();
});

 

 

As you can see we are attaching the onclick event listener to the button using jquery. And inside that we are getting the url of the image and also the convertType which approach the user has selected from the dropdown. Based upon that we are calling either the filereader or canvas method. We are using the ternary operator for that And lastly we are calling the function passing the image url and also the callback function inside it we are defining what should happen once the conversion takes place. We are showing all the things on the screen such as the actual image and the base64 code. And now we need to define the two methods guys that we are calling here

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
unction convertImgToDataURLviaCanvas(url, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
    canvas = null;
  };
  img.src = url;
}

 

 

As you can see inside the first approach we are using the canvas.toDataURL() method to convert the image in canvas to base64 data url. First of all we are drawing the image on the canvas using the drawImage()

 

 

JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
function convertFileToDataURLviaFileReader(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      callback(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();
}

 

 

And now in the second approach we are using the filereader class in javascript to read the remote image from the url and then we are using the readAsDataURL() method to convert the image to base64 data url code.

 

Now if you open the web app inside the browser you will see the below result as shown below

 

 

 

Recent Posts

  • Android Java Project to Download Multiple Images From URL With Progressbar & Save it inside Gallery
  • Android Java Project to Capture Image From Camera & Save it inside Gallery
  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme