简体   繁体   English

使用文件阅读器获取图像的宽度和高度

[英]Getting width & height of an image with filereader

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.我相信这应该有效,但我在 console.log 中只得到 0。 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)这需要将原始图像的宽度和高度输入到另一个脚本中(我将在之后进行,现在只需要在 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');
    };

You have to wait for the image to load.您必须等待图像加载。 Try handling the element inside .onload .尝试处理.onload的元素。

I've also simplified the process of setting the source of the two elements to how you should be doing it (with jQuery).我还简化了将两个元素的源设置为您应该如何操作的过程(使用 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);
    };
});

For me the solution of Austin didn't work, so I present the one worked for me:对我来说,奥斯汀的解决方案不起作用,所以我提出了一个对我有用的:

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

And if you find that assignment image.src = reader.result;如果你发现赋值image.src = reader.result; takes place after image.onload a bit wired, I think so too.发生在 image.onload 之后有点有线,我也这么认为。

Here's an answer inspired by Austin Brunkhorst with a callback for ascertaining image size in case you want to reuse the function elsewhere in your code.这是一个受 Austin Brunkhorst 启发的答案,带有用于确定图像大小的回调,以防您想在代码的其他地方重用该函数。

fileControl is assumed to be a jQuery element.假定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;
}

 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">

this is the way I have for AngularJS这是我对 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 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM