这是我的代码片段(删除了不必要的代码行):

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 enter image description here

The resized image looks like: enter image description here

已编辑:

如果有人好奇,我可以将已解决的代码版本粘贴到这里,以便您可以进行调整.在下面留下 comments .

推荐答案

您可以使用映像构造函数

const img = new Image();
img.src = imageDataUrl;
img.onload = () => {
   // img.width
   // img.height
 };

Javascript相关问答推荐

Webpack将懒惰加载的模块放入主块中

同步功能在中间停止

Promise.all立即跳到那时,而不是调用所有Promise

在JS中转换mysql UTC时间字段?

为什么有些库公开了执行相同任务的方法,但每个方法都处于同步/同步上下文中?

JavaScript:循环访问不断变化的数组中的元素

是否有方法在OpenWeatherMap API中获取过go 的降水数据?

深嵌套的ng-container元素仍然可以在Angular 布局组件中正确渲染内容吗?

被CSS优先级所迷惑

按下同意按钮与 puppeteer 师

Chromium会将URL与JS一起传递到V8吗?

显示图—如何在图例项上添加删除线效果?

邮箱密码重置链接不适用于已部署的React应用程序

回溯替代方式

警告框不显示包含HTML输入字段的总和

JavaScript:如果字符串不是A或B,则

构建器模式与参数对象输入

如何在FiRestore中的事务中使用getCountFromServer

如何使用[ModelJSON,ArrayBuffer]调用tf.loadGraphModelSync

为什么我的Navbar.css没有显示在本地主机页面上?