【问题标题】:Getting width & height of an image with filereader使用文件阅读器获取图像的宽度和高度
【发布时间】:2013-03-07 15:18:12
【问题描述】:

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

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

【问题讨论】:

  • 如果您的图像相对较大 (>500 KB),您可以使用 EXIF 库。然后,您只需阅读具有宽度和高度标签的 EXIF 标头。

标签: javascript dom filereader


【解决方案1】:

fileChangeEventHeader(fileInput) {
    const oFReader = new FileReader();
    oFReader.readAsDataURL(fileInput.target.files[0]);
    oFReader.onload = (event: any) => {
      var image = new Image();
      image.src = event.target.result;
      image.onload = function () {
        console.log(`width : ${image.width} px`, `height: ${image.height} px`);
      };
    };
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<input type="file" name="profile_img" accept="image/*" (change)="fileChangeEventHeader($event)"
                  class="input-file">

【讨论】:

    【解决方案2】:

    这是一个受 Austin Brunkhorst 启发的答案,带有一个用于确定图像大小的回调,以防您想在代码的其他地方重用该函数。

    fileControl 被假定为一个 jQuery 元素。

    function didUploadImage(fileControl) {      
       // Render image if file exists.
       var domFileControl = fileControl[0];
       if (domFileControl.files && domFileControl.files[0]) {
          // Get first file.
          var firstFile = domFileControl.files[0];
    
          // Create reader.
          var reader = new FileReader();
    
          // Notify parent when image read.
          reader.onload = function(e) {
             // Get image URL.
             var imageURL = reader.result;
    
            // Get image size for image.
            getImageSize(imageURL, function(imageWidth, imageHeight) {
                // Do stuff here.
            });
          };
    
          // Read image from hard disk.
          reader.readAsDataURL(firstFile);
    
          // Print status.
          console.log("Uploaded image: " + firstFile.name);
       }
    }
    
    
    function getImageSize(imageURL, callback) {      
       // Create image object to ascertain dimensions.
       var image = new Image();
    
       // Get image data when loaded.
       image.onload = function() {      
          // No callback? Show error.
          if (!callback) {
             console.log("Error getting image size: no callback. Image URL: " + imageURL);
    
          // Yes, invoke callback with image size.
          } else {
             callback(this.naturalWidth, this.naturalHeight);
          }
       }
    
       // Load image.
       image.src = imageURL;
    }
    

    【讨论】:

      【解决方案3】:

      这就是我对 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
      
      
                });

      【讨论】:

        【解决方案4】:

        奥斯汀的解决方案对我来说不起作用,所以我提出一个对我有用的解决方案:

        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 有点连线之后,我也这么认为。

        【讨论】:

        • 图像加载是异步的并不是连线的。 src 中的所有数据都必须解码,如果 src 是链接,则必须加载并解码为图像,如果也是 base64。所以这很自然:-)
        【解决方案5】:

        您必须等待图像加载。尝试处理.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);
            };
        });
        

        【讨论】:

        • 太好了,非常感谢。我误以为文件会通过 readAsDataURL 调用加载。
        • reader.onload 在文件系统完成从硬盘读取文件时调用。 image.onload 本质上是在图像对象在浏览器中缓冲图像数据时调用的。我明白你怎么可能误解了 onload 函数;不过很高兴能得到帮助。
        • 注意:这仅在您使用“reader.readAsDataURL”时有效。使用“reader.readAsBinaryString”,您必须采用不同的方式。
        • 您最终需要从图像内容中获取数据 uri,因此使用.readAsBinaryString() 是没有意义的。
        • @AustinBrunkhorst 如果您将相同的二进制字符串发送到服务器(文件上传),这并不是毫无意义的。使用 readAsBinaryString() 比从数据 URL 在 javascript 中手动创建要快得多。
        猜你喜欢
        • 2020-10-15
        • 2010-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多