0

I am convertin image to base64 string using following code

  function getBase64Image() {
    p = document.getElementById("fileUpload").value;
    img1.setAttribute('src', p);
    canvas.width = img1.width;
    canvas.height = img1.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img1, 0, 0);
    var dataURL = canvas.toDataURL("image/jpg");

    $("#b64").val(dataURL);
}

But what I am getting in dataURL is Data; and there is not base64 string contained.

How can I fetch base64 string from image?

user786
  • 3,902
  • 4
  • 40
  • 72

2 Answers2

0

Here's a simple example:

// assuming that you have jQuery lib

$('#fileUpload').on('change', function(e) {
  if (this.files.length === 0) return;

  var imageFile = this.files[0];
  var reader = new FileReader();

    // when reading of image file completes
  reader.onloadend = function() {
    var tempImg = new Image();
    tempImg.src = reader.result;

        // when image is loaded
    tempImg.onload = function() {
      canvas.getContext("2d").drawImage(tempImg, 0, 0);
    }

  }

  // start reading
  reader.readAsDataURL(imageFile);
});

Hope this helps!!

Pradeep
  • 3,093
  • 17
  • 21
0

i think this could work if you use load callback because the loading is async. not sure what your fileUpload is tho, but if's a text field pasting a url

function getBase64Image() {
    p = document.getElementById("fileUpload").value;
    img1.setAttribute('src', p);
    img1.setAttribute('load', fileLoaded);  
    function fileLoaded(e) {
      canvas.width = img1.width;
      canvas.height = img1.height;
      var ctx = canvas.getContext("2d");
      ctx.drawImage(img1, 0, 0);
      var dataURL = canvas.toDataURL("image/jpeg");
      $("#b64").val(dataURL);
    }
}

the image type is also image/jpeg. jpg won't work or, it will return png instead since it isn't valid. and cross-origin can be a problem iirc.

torox
  • 460
  • 1
  • 3
  • 11
  • Never use `setAttribute` to attach an event listener. In some cases, you can use its `onload` property, but the best way is to use `Element.addEventListener` method. Using `setAttribute` will set the attribute to the result of `handler.toString()`, you will loose all scoped variables, and I'm not even sure the event will fire... – Kaiido Jul 18 '16 at 04:38