获取宽度 &带有文件阅读器的图像高度 [英] Getting width & height of an image with filereader

查看:14
本文介绍了获取宽度 &带有文件阅读器的图像高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个图像调整大小/裁剪,我想在他们在模式(引导程序)中对其进行编辑后显示实时预览.这应该工作,我相信,但我只是在console.log中得到0.这需要将原始图像的宽度和高度输入到另一个脚本中(稍后我会这样做,现在只需要在 console.log/a 变量中使用它们)

I am building an image resize/crop, and I'd like to show a live preview after they've edited it in a modal (bootstrap). This should work, I believe, but I just get 0 in console.log. This requires feeding the width and the height of the original image into another script (which I'll do after, just need them in console.log/a variable for now)

function doProfilePictureChangeEdit(e) {
    var files = document.getElementById('fileupload').files[0];
    var reader = new FileReader();
    reader.onload = (function(theFile) {
        document.getElementById('imgresizepreview').src = theFile.target.result;

        document.getElementById('profilepicturepreview').src = theFile.target.result;
      }
    );
    reader.readAsDataURL(files);
    var imagepreview = document.getElementById('imgresizepreview');
    console.log(imagepreview.offsetWidth);
    $('img#imgresizepreview').imgAreaSelect({
        handles: true,
        enable: true,
        aspectRatio: "1:1",
        onSelectEnd: preview
    });
    $('#resizeprofilepicturemodal').modal('show');
    };

推荐答案

您必须等待图像加载.尝试处理 .onload 中的元素.

You have to wait for the image to load. Try handling the element inside .onload.

我还简化了将两个元素的源设置为您应该如何操作的过程(使用 jQuery).

I've also simplified the process of setting the source of the two elements to how you should be doing it (with jQuery).

reader.onload = (function(theFile) { 
    var image = new Image();
    image.src = theFile.target.result;

    image.onload = function() {
        // access image size here 
        console.log(this.width);

        $('#imgresizepreview, #profilepicturepreview').attr('src', this.src);
    };
});

这篇关于获取宽度 &带有文件阅读器的图像高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆