Happy Coconut
Happy Coconut

Reputation: 1063

take picture from Input field and convert to base64

I want to be able to take picture from PC and uploaded to server. So far I have managed to take a picture from a div, convert it to base64 and send it to server side. This works without a problem.

My HTML:

  <img src="AvatarIMG/Goofy.jpg" id="img" width="100" height="100">

My JavaScript:

  $('#but_upload').click(function () {
            var c = document.createElement('canvas');
            var img = document.getElementById('img');
            c.height = img.naturalHeight;
            c.width = img.naturalWidth;
            var ctx = c.getContext('2d');
            console.log(ctx);
            ctx.drawImage(img, 0, 0, c.width, c.height, 0, 0, c.width, c.height);
            var base64String = c.toDataURL();

            $.ajax({
                url: 'Avatar',
                method: 'PUT', 
                contentType: 'application/json',
                headers: {
                    'Authorization': 'Bearer '
                        + sessionStorage.getItem("accessToken")
                },
                dataType: "text",
                data: JSON.stringify(base64String),
                success: function (data) {
                },
                error: function (jQXHR) {
                }
            });
        });

However i want to be able to pick a picture from my local computer and then upload it but so far no luck... This is what I have tried...

My HTML:

 <input id="uploadImage" type="file" name="myPhoto" />

My JavaScript:

 $('#but_upload').click(function () {

            var img = document.createElement("img");
            img.height = 30;
            img.width = 20;

            var oFReader = new FileReader();
            oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

            oFReader.onload = function (oFREvent) {
                img.src = oFREvent.target.result;
            };

            var c = document.createElement('canvas');
            c.height = img.naturalHeight;
            c.width = img.naturalWidth;
            var ctx = c.getContext('2d');

            ctx.drawImage(img, 0, 0, c.width, c.height, 0, 0, c.width, c.height);
            var base64String = c.toDataURL();



            $.ajax({
                url: 'Avatar',
                method: 'PUT', 
                contentType: 'application/json',
                headers: {
                    'Authorization': 'Bearer '
                        + sessionStorage.getItem("accessToken")
                },
                dataType: "text",
                data: JSON.stringify(base64String),
                success: function (data) {
                },
                error: function (jQXHR) {
                }
            });
        });

Some help pls.

Upvotes: 0

Views: 60

Answers (1)

soktinpk
soktinpk

Reputation: 3888

The issue is that you need to wait for img.onload, because you are trying to draw it onto the canvas before the image even loads.

$('#but_upload').click(function() {

  var img = document.createElement("img");

  var oFReader = new FileReader();
  oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

  oFReader.onload = function(oFREvent) {
    img.src = oFREvent.target.result;
  };

  img.onload = function() {
    var c = document.createElement('canvas');
    c.height = img.naturalHeight;
    c.width = img.naturalWidth;
    var ctx = c.getContext('2d');

    ctx.drawImage(img, 0, 0, c.width, c.height, 0, 0, c.width, c.height);
    var base64String = c.toDataURL();
    console.log(base64String);
    // upload your stuff
  }


  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="uploadImage" type="file" name="myPhoto" />
  <input id="but_upload" type="submit" />
</form>

On the other hand, since FileReader reads as a DataURL, you could simply use what it has already read

$('#but_upload').click(function() {

  var img = document.createElement("img");

  var oFReader = new FileReader();
  oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

  oFReader.onload = function(oFREvent) {
    img.src = oFREvent.target.result;
    var base64String = oFREvent.target.result;
    console.log(base64String);
    // do your uploading stuff here
  };


  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="uploadImage" type="file" name="myPhoto" />
  <input id="but_upload" type="submit" />
</form>

Upvotes: 1

Related Questions