119

I want to set the Image source to a base64 source but it does not work:

JSfiddle.net/NT9KB

<img id="img" src="" />

the JavaScript

document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=="
poppel
  • 1,543
  • 4
  • 17
  • 22

4 Answers4

185

Remove the line-breaks in the base64:

document
    .getElementById('img')
    .src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
Kevin Boucher
  • 16,426
  • 3
  • 48
  • 55
  • thx, I will accept in 10 minutes, why is setAttribute better? – poppel May 08 '13 at 20:27
  • @poppel I don't think it matters, but my first attempt to fix your fiddle was to use `setAttribute`. It was after that failed that I noticed the line-breaks in the base64 encoding. (Since I was rushing to get an answer submitted, I did not try it with `src=` after fixing the line-breaks.) – Kevin Boucher May 08 '13 at 20:47
38

In case you prefer to use jQuery to set the image from Base64:

$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
Faris Zacina
  • 14,056
  • 7
  • 62
  • 75
  • 6
    @TruthSerum we are not using it, since we switch to a React stack. But for fun, do you have statistical evidence to prove your claim? Do you really think that there are no legacy web apps using jQuery? Your comment is based on your personal opinion, and really a waste of my personal time. Also if you check the project, it is still maintained and has a huge follower base. https://github.com/jquery/jquery/commits/master – Faris Zacina Apr 25 '16 at 17:33
  • 6
    Also @TruthSerum here are some stats, since you didn't get a chance to check them before posting your comment: https://www.google.com/trends/explore#q=jquery%2C%20angular&cmpt=q&tz=Etc%2FGMT-2 – Faris Zacina Apr 25 '16 at 17:36
  • These days, `prop` should be used instead of `attr` for updating the DOM. `attr` refers to original page state on loading. – AntonChanning Aug 05 '19 at 11:30
9
img = new Image();
img.src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
img.outerHTML;
"<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">"
zzart
  • 11,207
  • 5
  • 52
  • 47
6

Your problem are the cr (carriage return)

http://jsfiddle.net/NT9KB/210/

you can use:

document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="