Hello I have the following image:
with size 750x554
I load the iamge into a img tag, of the following way:
<input type="file" accept="image/*"
onchange="document.getElementById('character').src = window.URL.createObjectURL(this.files[0]);">
<img id="character" alt="your image" width="100" height="100" />
And in order to convert this image into a base64 I use canvas with the following code:
let canvas = document.createElement("canvas");
canvas.width = img.width
canvas.height = img.height
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
let dataURL = canvas.toDataURL("image/png");
But the result that I get is a cropped image as you can see here
How can solve this, and get the image in base64?
Thanks.
you need to set the canvas to the size of the image and you need to wait for the image to actually load before trying to draw it.
document.querySelector('input').addEventListener('change', function() { const url = window.URL.createObjectURL(this.files[0]); const img = document.getElementById('character'); img.addEventListener('load', function() { let canvas = document.createElement("canvas"); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; let ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); let dataURL = canvas.toDataURL("image/png"); // show image const i = new Image(); i.src = dataURL; document.body.appendChild(i); }); img.src = url; });
<input type="file" accept="image/*"> <img id="character" alt="your image" width="100" height="100" />
I think here problem is with your image tag since you have specified the image's width and height as 100
<img id="character" alt="your image" width="100" height="100" />
So instead of this just give the actual height and width to image tag.
Happy Coding !!!
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.