Terry Gilliver
Posts: 0
Joined: Fri Apr 18, 2014 8:45 pm

Convert a local image to a Data URI

I am trying to convert an image to a data uri.

i found the following function on the Internet:

code//get image dataurl
function getBase64FromImageUrl(url) {
var img = new Image();

Code: Select all

 img.setAttribute('crossOrigin', 'anonymous'); 

 img.onload = function () { 
     var canvas = document.createElement("canvas"); 
     canvas.width =this.width; 
     canvas.height =this.height; 

     var ctx = canvas.getContext("2d"); 
     ctx.drawImage(this, 0, 0); 

     var dataURL = canvas.toDataURL("image/jpeg"); 

     alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, "")); 
 }; 

 img.src = url; 

}/code

If I try and use it to convert a local file i get the following console error:
Not allowed to load local resource: file:///C:/fakepath/220px-Nerium_oleander_flowers_leaves.jpg

Do you know of a way to convert a local image to a data url?

Terry Gilliver
Posts: 0
Joined: Fri Apr 18, 2014 8:45 pm

Convert a local image to a Data URI

Found a solution:

define a javascript function:

code File.prototype.convertToBase64 = function(callback){
var reader = new FileReader();
reader.onload = function(e) {
callback(e.target.result)
};
reader.onerror = function(e) {
callback(null);
};
reader.readAsDataURL(this);
};/code

add a call in the change event of the input component of type 'file':

codevar selectedFile = this.files[0];
selectedFile.convertToBase64(function(base64){
Apperyio('base64_image').text(base64);
});/code

'base64_image' is the name of a label where the output will be stored.
This might be of use to others.

Serhii Kulibaba
Posts: 150
Joined: Tue Aug 27, 2013 1:47 pm

Convert a local image to a Data URI

Hello Terry,

Thank you for update! Glad it works now!

Return to “Issues”