简体   繁体   English

在javascript或jQuery中将img src转换为输入文件

[英]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? 如何将img src转换为文件类型的输入?

I'm using webcamjs and it gives me a data_uri for an image src that looks like this 我正在使用webcamjs,它为我提供了一个看起来像这样的图像src的data_uri

 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 其中#id-file是此类文件类型的输入

 <input type="file" id="id-file" name="id-file" accept=".jpeg,.jpg,.png"> 

Try using a base 64 convert like this post: CONVERT Image url to Base64 尝试使用base 64像这样的帖子进行转换:将图片网址转换为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! 然后将base64字符串传递给表单,因为它包含所有图像数据!

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM