Getting width & height of an image with filereader

后端 未结 5 1341
小鲜肉
小鲜肉 2020-11-30 23:36

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 ge

5条回答
  •  粉色の甜心
    2020-11-30 23:59

    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.

    fileControl is assumed to be a jQuery element.

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

提交回复
热议问题