chuckd
chuckd

Reputation: 14520

Converting a img src to a input file in javascript or jquery

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">

Upvotes: 2

Views: 8113

Answers (1)

Patrick Murphy
Patrick Murphy

Reputation: 2329

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.

Upvotes: 1

Related Questions