简体   繁体   中英

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.

Curious is there any alternative way to get the data url of the uploaded image?

Thanks.

You don't need a canvas. You can just use the 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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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