Converting a local image to base64 using JavaScript

Raja Ramesh picture Raja Ramesh · Mar 5, 2012 · Viewed 8.3k times · Source

Iam doing a project in html, javascript only. I have a function that convert image to base64, see the code below.

function getBase64Image()
{
    p = document.getElementById("picField").value;
    img.setAttribute('src', p);
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    var r = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    base64 = r;
    alert(base64);
}

but the problem is when I deployed my website, means when I placed my html file on iis, its not working, means in local file system it is showing complete base 64 format like iVb...., but on iis it giving base64 code as just "base,". so why it is not working on iis i dont know, so please help me and send me html file that will work on iis too.

Answer

Pekka picture Pekka · Mar 5, 2012

I'm fairly sure you have a Same Origin Policy problem.

When you run your page on IIS, it runs in a different context than locally: Instead of a file:// URL, it runs on a http:// one.

What you are trying to do is fetch a local image file and load it into a canvas on a remote site. That is not possible using traditional JavaScript for security reasons. (I'm not sure how this works even locally - in my understanding, it shouldn't. But anyway.)

You will need to use the HTML 5 file API which allows JavaScript direct access to local files. I'll look whether I can dig up some related SO questions.

Update: this should help: