这是我的代码片段(删除了不必要的代码行):
let imgInput = document.getElementById('id_photo');
imgInput.addEventListener('change', function (e) {
if (e.target.files) {
for (let i = 0; i < e.target.files.length; i++) {
let imageFile = e.target.files[i];
var reader = new FileReader();
reader.onload = function (e) {
var img = document.getElementById(nevermindID);
img.onload = function() {
var shape = resizeImage(img) // resizing image for future canvas drawing, returns [width, height] (resized)
var canvas = document.createElement("canvas")
canvas.width = shape[0]
canvas.height = shape[1]
var ctx = canvas.getContext("2d")
ctx.drawImage(img, 0, 0, shape[0], shape[1])
// converting to base64 logic and the rest code
}
img.src = e.target.result;
}
reader.readAsDataURL(imageFile);
}
}
});
我想得到上传的原始图像的宽度和高度,以便我可以调整它的大小.我无法从imageFile执行此操作,因为它返回undefined,也无法从img变量中获得它,因为它最初取决于我的css(在css中,<img>
标记位于<div>
标记中,它不是全屏的,假设它是400像素).因此,相应地,如果我上传5000x5000图像,它将不会是原来的大小(希望你得到它).我的问题是,因为我的css调整了div和其中的元素的大小,我无法获得原始图像的正常宽度和高度,所以我可以调整它的大小,然后用canvas绘制,然后将其转换为base64.
我try 将此代码添加到img.onload:
var blobURL = URL.createObjectURL(imageFile)
在这里,我访问我的原始图像(imageFile),为其创建blob并获得blob链接.但我无法访问blob链接图像的宽度和高度.有什么建议吗?
注:我认为问题在于img.onload本身.在这一行中,我通过了img:
ctx.drawImage(img, 0, 0, shape[0], shape[1])
FYI. This is how it looks when I upload my image. It is about 90x90 pixels here. And that causes the problem with canvas, as img.onload takes those dimensions (90x90) and not the original dimensions which is about 5000x5000
已编辑:
如果有人好奇,我可以将已解决的代码版本粘贴到这里,以便您可以进行调整.在下面留下 comments .