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

1

2 Answers 2

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 .

Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

wait, you "can't" encode it if was served with cors or a proxy?
You can't encode the image if it was served from another domain without CORS. If it was served with the right CORS header then it's fine.
@dandavis I'm not a native English speaker but doesn't "apart" convey the same meaning than "except" here ?
well, it was enough that i didn't understand it without my morning coffee. you could say "apart from cases where" instead of "except if"...
@dandavis Thanks for that English lesson :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.