2013-03-19 142 views
27

我正在构建图像调整大小/作物,并且我想在模型(引导程序)中编辑它之后显示实时预览。这个应该工作,我相信,但我只是在console.log中得到0。这就需要喂养的宽度和原始图像的高度到另一个脚本(我将在以后做什么,只需要他们的console.log /现在一个变量)使用filereader获取图像的宽度和高度

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'); 
    }; 

回答

70

你要等待图像加载。尝试处理.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); 
    }; 
}); 
+0

大的方式,非常感谢。我误以为这些文件会加载readAsDataURL调用。 – 2013-03-19 04:34:02

+1

当文件系统完成从硬盘读取文件时调用'reader.onload'。本质上,图像对象已经在浏览器中缓冲了图像数据时调用'image.onload'。我看你怎么会误解onload函数;很高兴有帮助。 – 2013-03-19 05:45:44

+1

注意:这仅适用于使用“reader.readAsDataURL”的情况。用“reader.readAsBinaryString”你必须采取不同的方式。 – 2014-01-30 14:25:05

15

对我来说奥斯汀的解决没有工作,所以我提出了我的一个工作:

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]); 

如果您发现作业image.src = reader.result; image.onload有点有线之后发生, 我也这么认为。

+0

它没有连接图像加载是异步的。如果src是链接,则必须将src中的所有数据解码,如果base64也必须将其加载并解码为图像。所以这很自然:-) – BrightShadow 2016-05-19 08:26:17

+0

@BrightShadow这是正确的答案。 – 2016-07-16 02:26:59

0

这是我对AngularJS

  fileReader.readAsDataUrl($scope.file, $scope).then(function(result) { 
 
       var image = new Image(); 
 
       image.src = result; 
 
       image.onload = function() { 
 
        console.log(this.width); 
 
       }; 
 
       $scope.imageSrc = result; //all I wanted was to find the width and height 
 

 

 
      });