2

how to convert image url to base64 encoded data url without using html5 canvas object.

canvas.todataURL()

I am gettting base64 data using canvas.todataURL, but it fails to read remote url's, so I want to convert my image url to dataurl with out using canvas.todataURL() and use it in my application.

HOw can I to do this.

atluriajith
  • 762
  • 3
  • 17
  • 41
  • You can actually use canvas.toDataUrl() with remote images if you use [Cross-origin resource sharing](https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image). The browser support is still pretty poor though. – Strille Sep 19 '13 at 13:43
  • 1
    @Strille: Update--Good news! Actually, most modern browsers do support cross-browser XMLHttpRequests **Good on:** ie10,FF,webkit,ios,blackberry, **Awkward implementation on:** ie9, **no support on:** opera-mini. And of course ie<9 has no canvas support. Enabling cross-domain sharing on the server hosting your images can be tricky, but once set, you're good. Some "cloud" image servers like dropbox.com offer cross-domain by default. – markE Sep 19 '13 at 17:14

2 Answers2

2

You can use this code-

HTML-

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

javascript-

    <script>
     var c = document.getElementById("myCanvas");
     var ctx = c.getContext("2d");
     var img = document.getElementById("preview");
     ctx.drawImage(img, 10, 10);
     alert(c.toDataURL());
    </script>

found it here- How to get base64 encoded data from html image

Community
  • 1
  • 1
Mandeep Singh
  • 983
  • 8
  • 9
0

You can't do it purely in javascript without using canvas.toDataUrl(). You would have to do something server-side. Basically create a simple service which takes an url to an image as parameter and then returns that image as a base64 string.

Strille
  • 5,741
  • 2
  • 26
  • 40
  • hmm... yes i did creating some service to send image url and return base64 string but in my application there is no chance to use any server side script, It is purely on html and javascript.. that is why I'm trying to do it on pure javascript.. – atluriajith Sep 19 '13 at 12:36