Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get base64 encoded data from html image

I have a registration form where users can choose an avatar. They have 2 possibilities:

  1. Choose a default avatar
  2. Upload their own avatar

In my HTML page I have this.

<img id="preview" src="img/default_1.png"> 

It displays the chosen avatar. I use the File Api to let users upload their own image. That makes the src of the HTML image to something like this.

<img id="preview" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA... /> 

When they post the registration form. The data will be sent to a REST service. I can send the base64 encoded data when a user uploaded an avatar himself. But how do I handle the default avatar? It is an url instead of base64 encoded data.

like image 718
Jonas Anseeuw Avatar asked Apr 02 '13 09:04

Jonas Anseeuw


People also ask

Can we convert image URL to Base64?

We can convert an image to a base64 URL by loading the image with the given URL into the canvas and then call toDataURL to convert it to base64.

How do I display Base64 in HTML?

Use the img Tag to Display Base64 Image in HTML We can specify the URL of the image in the src attribute of the img tag. We can display base64 images by providing the information about the image in the src attribute. We need to define the accurate content type, content-encoding, and charset in the src attribute.


2 Answers

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG"> <canvas id="myCanvas" /> 

var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var img = document.getElementById("preview"); ctx.drawImage(img, 10, 10); alert(c.toDataURL()); 
like image 146
Chamika Sandamal Avatar answered Sep 20 '22 23:09

Chamika Sandamal


You can also use the FileReader class :

    var reader = new FileReader();     reader.onload = function (e) {         var data = this.result;     }     reader.readAsDataURL( file ); 
like image 26
httpete Avatar answered Sep 18 '22 23:09

httpete