1

I'm trying to encode an image (jpg) to base64 using IE9. I tried the following code:

var canvas = document.createElement("canvas");
    canvas.width = document.getElementById('myImage').width; 
    canvas.height = document.getElementById('myImage').height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(document.getElementById('myImage'), 0, 0);

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

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

I got the error : DOM Exception: SECURITY_ERR (18) when I call toDataURL method.

Any idea what I'm doing wrong here?

Thanks

d_alves
  • 13
  • 1
  • 4
  • possible duplicate of [Base64 encoding and decoding in client-side Javascript](http://stackoverflow.com/questions/2820249/base64-encoding-and-decoding-in-client-side-javascript) – davidcondrey Sep 30 '14 at 09:06

2 Answers2

1

You need to use php or any other server side languages for encode an image to a base64 encoding.Use jquery ajax for this purpose , encode it on server side and pass it to the client side .

You can encode text to base64 encoding .There is a nice project in Codeplex Click here

Iam not sure you can encode images ,give a try .

Jijo John
  • 1,375
  • 9
  • 21
0

Due to same origin policy, you can't encode a canvas when you drew on it something coming from another origin than your page, except if :

  • the drawn image was served with relevant CORS headers
  • you serve it through a proxy so that the browser thinks it's the same origin

Note that if you open your page in file://, then any image will be seen as from another origin.

vector
  • 7,334
  • 8
  • 52
  • 80
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758