Подтвердить что ты не робот

Получение ширины и высоты изображения с помощью filereader

Я создаю изображение resize/crop, и я бы хотел показать предварительный просмотр в прямом эфире после того, как он отредактировал его в модальном (bootstrap). Это должно работать, я считаю, но я просто получаю 0 в console.log. Это требует подачи ширины и высоты исходного изображения в другой script (который я буду делать после этого, просто нужно их в 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');
    };
4b9b3361

Ответ 1

Вам нужно дождаться загрузки изображения. Попробуйте обработать элемент внутри .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);
    };
});

Ответ 2

Для меня решение Остина не сработало, поэтому я представляю, что тот работал у меня:

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 немного подключен, я тоже так думаю.

Ответ 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

Вот ответ, вдохновленный Остином Брунхорстом, с обратным вызовом для определения размера изображения на тот случай, если вы захотите повторно использовать функцию в другом месте вашего кода.

Предполагается, что 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;
}