使用filereader获取图像的宽度和高度

Mar*_*son 39 javascript dom filereader

我正在构建一个图像调整大小/裁剪,我想在他们用模态(bootstrap)编辑它之后显示一个实时预览.我相信这应该可行,但我在console.log中得到0.这需要将原始图像的宽度和高度输入另一个脚本(我将在之后执行,现在只需要它们在console.log /变量中)

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');
    };
Run Code Online (Sandbox Code Playgroud)

Aus*_*rst 97

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

我还简化了将两个元素的源设置为应该如何操作的过程(使用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);
    };
});
Run Code Online (Sandbox Code Playgroud)

  • `reader.onload` 在文件系统完成从硬盘读取文件时被调用。`image.onload` 本质上是在图像对象在浏览器中缓冲图像数据时调用的。我明白你怎么可能误解了 onload 函数;很高兴得到帮助。 (4认同)

and*_*abs 25

对我来说奥斯汀的解决方案没有用,所以我提出了一个适合我的方案:

var reader = new FileReader;

reader.onload = function() {
    var image = new Image();

    image.src = reader.result;

    image.onload = function() {
        alert(image.width);
    };

};

reader.readAsDataURL(this.files[0]);
Run Code Online (Sandbox Code Playgroud)

如果你发现这个任务image.src = reader.result;发生在image.onload有线之后,我也是这么认为的.