简体   繁体   English

Javascript 将上传的图片转换为 canvas.toDataURL()

[英]Javascript convert uploaded image to canvas.toDataURL()

I need the data url of the image to be in:我需要图像的数据网址在:

 'data:image/jpeg;base64,""'.

format格式

So my first solution is to render the uploaded image as an Image element, and use canvas.drawImage(imageElement) , to get canvas.toDataURL() , but I'm getting the canvas has been tainted Error.所以我的第一个解决方案是将上传的图像渲染为 Image 元素,并使用canvas.drawImage(imageElement)来获取canvas.toDataURL() ,但我得到的是 canvas has been tainted 错误。

Curious is there any alternative way to get the data url of the uploaded image?好奇有没有其他方法可以获取上传图片的数据 url?

Thanks.谢谢。

You don't need a canvas.你不需要画布。 You can just use the File API .您可以只使用File API

 const element = document.getElementById('file'); element.addEventListener('change', ({target: {files}}) => { const [image] = files; const reader = new FileReader(); reader.onload = ({target: {result}}) => console.log(result); reader.readAsDataURL(image); });
 <input id="file" type="file">

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

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