allen
allen

Reputation: 309

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.

Upvotes: 0

Views: 134

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97151

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

Upvotes: 2

Related Questions