fightstarr20
fightstarr20

Reputation: 12568

readAsDataURL - Get Image as Base64

I am loading an image using readAsDataURL like this...

function previewFile() {

	console.log('Start Function')
  
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.addEventListener("load", function () {
    preview.src = reader.result;
  }, false);

  if (file) {
    reader.readAsDataURL(file);
  }
  
  canvas = document.getElementById("preview");
  imageData = canvas.toDataURL("image/jpeg");
  
  console.log(imageData)
  
}
<input type="file" onchange="previewFile()"><br>
<img id="preview" src="https://dummyimage.com/600x400/000/fff" height="200" alt="Image preview...">

I am trying to get the previewed image as base64 data, I have tried to use toDataURL but it is returning an error.

Where am I going wrong?

Upvotes: 1

Views: 98

Answers (1)

Marouen Mhiri
Marouen Mhiri

Reputation: 1667

Your HTML Element should be a canvas and not an image:

<input type="file" onchange="previewFile()"><br>
<canvas id="preview" height="200" />

Upvotes: 1

Related Questions