2

How do I convert from a img src to a input of type file?

I'm using webcamjs and it gives me a data_uri for an image src that looks like this

Webcam.snap(function(data_uri) {
  document.getElementById('my_result_front').innerHTML 
      = '<img id="webcamImageToCropFront" src="' + data_uri + '"/>';
});

and now I need to convert the image source into a file that I can pass to my form like this

const data = new FormData();
data.append('file', document.querySelector('#id-file').files[0]);

where #id-file is a input of type file like this

<input type="file" id="id-file" name="id-file" accept=".jpeg,.jpg,.png">
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • 1
    Create a [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob) and pass that as the second parameter to append, as is supports `Blob` or `File`. – Get Off My Lawn Dec 12 '18 at 22:19

1 Answers1

1

Try using a base 64 convert like this post: CONVERT Image url to Base64

function getBase64Image(img) {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0);
  var dataURL = canvas.toDataURL("image/png");
  return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

var base64 = getBase64Image(document.getElementById("webcamImageToCropFront"));

Then pass your base64 string to the form as it contains all of the image data!

Hope that helps.

Patrick Murphy
  • 2,311
  • 14
  • 17