【问题标题】:How to get image width and height using JavaScript before upload?如何在上传前使用 JavaScript 获取图像宽度和高度?
【发布时间】:2016-05-08 17:23:33
【问题描述】:

如何在上传前使用 Javascript 获取图像宽度和高度?我试图测试我的代码,但它不起作用。我怎样才能做到这一点?

https://jsfiddle.net/r78qkjba/1/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input name="offer_image_1" onchange="check_thumbnail_image_format_fn()" type="file" id="offer_image_1" />
<script>
    function check_thumbnail_image_format_fn() {
        var offer_image_1_data = document.getElementById("offer_image_1");
        var offer_image_1_data_file = offer_image_1_data.files[0];
        var offer_image_1_data_file_width = offer_image_1_data_file.width;
        var offer_image_1_data_file_height = offer_image_1_data_file.height;
        alert(offer_image_1_data_file_width);
        alert(offer_image_1_data_file_height);
    };
</script>

【问题讨论】:

    标签: javascript jquery html css ajax


    【解决方案1】:

    希望下面的代码对你有所帮助。

    var _URL = window.URL || window.webkitURL;
    $("#offer_image_1").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            alert(this.width + " " + this.height);
        };
        img.src = _URL.createObjectURL(file);
    }
    });
    

    您不需要在输入节点添加 onchange 事件。 此代码取自 Check image width and height before upload with Javascript

    【讨论】:

      【解决方案2】:

      HTML5 和File API

      这是未注释的工作代码 sn-p 示例

      window.URL    = window.URL || window.webkitURL;
      var elBrowse  = document.getElementById("browse"),
          elPreview = document.getElementById("preview"),
          useBlob   = false && window.URL; // `true` to use Blob instead of Data-URL
      
      function readImage (file) {
        var reader = new FileReader();
        reader.addEventListener("load", function () {
          var image  = new Image();
          image.addEventListener("load", function () {
            var imageInfo = file.name    +' '+
                            image.width  +'×'+
                            image.height +' '+
                            file.type    +' '+
                            Math.round(file.size/1024) +'KB';
            elPreview.appendChild( this );
            elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
          });
          image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
          if (useBlob) {
            window.URL.revokeObjectURL(file); // Free memory
          }
        });
        reader.readAsDataURL(file);  
      }
      
      elBrowse.addEventListener("change", function() {
        var files  = this.files;
        var errors = "";
        if (!files) {
          errors += "File upload not supported by your browser.";
        }
        if (files && files[0]) {
          for(var i=0; i<files.length; i++) {
            var file = files[i];
            if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
              readImage( file ); 
            } else {
              errors += file.name +" Unsupported Image extension\n";  
            }
          }
        }
        if (errors) {
          alert(errors); 
        }
      });
      #preview img{height:100px;}
      <input id="browse" type="file"  multiple />
      <div id="preview"></div>

      对图像预览区域使用输入和 div

      <input id="browse" type="file" multiple>
      <div id="preview"></div>
      

      让我们也使用 CSS 将生成的图像保持在合理的高度:

      #preview img{ height:100px; }
      

      JavaScript

      window.URL    = window.URL || window.webkitURL;
      var elBrowse  = document.getElementById("browse"),
          elPreview = document.getElementById("preview"),
          useBlob   = false && window.URL; // `true` to use Blob instead of Data-URL
      
      
      // 2.
      function readImage (file) {
      
        // 2.1
        // Create a new FileReader instance
        // https://developer.mozilla.org/en/docs/Web/API/FileReader
        var reader = new FileReader();
      
        // 2.3
        // Once a file is successfully readed:
        reader.addEventListener("load", function () {
      
          // At this point `reader.result` contains already the Base64 Data-URL
          // and we've could immediately show an image using
          // `elPreview.insertAdjacentHTML("beforeend", "<img src='"+ reader.result +"'>");`
          // But we want to get that image's width and height px values!
          // Since the File Object does not hold the size of an image
          // we need to create a new image and assign it's src, so when
          // the image is loaded we can calculate it's width and height:
          var image  = new Image();
          image.addEventListener("load", function () {
      
            // Concatenate our HTML image info 
            var imageInfo = file.name    +' '+ // get the value of `name` from the `file` Obj
                            image.width  +'×'+ // But get the width from our `image`
                            image.height +' '+
                            file.type    +' '+
                            Math.round(file.size/1024) +'KB';
      
            // Finally append our created image and the HTML info string to our `#preview` 
            elPreview.appendChild( this );
            elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
          });
      
          image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
      
          // If we set the variable `useBlob` to true:
          // (Data-URLs can end up being really large
          // `src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAA...........etc`
          // Blobs are usually faster and the image src will hold a shorter blob name
          // src="blob:http%3A//example.com/2a303acf-c34c-4d0a-85d4-2136eef7d723"
          if (useBlob) {
            // Free some memory for optimal performance
            window.URL.revokeObjectURL(file);
          }
        });
      
        // 2.2
        // https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
        reader.readAsDataURL(file);  
      
      }
      
      // 1.
      // Once the user selects all the files to upload
      // that will trigger a `change` event on the `#browse` input
      elBrowse.addEventListener("change", function() {
      
        // Let's store the FileList Array into a variable:
        // https://developer.mozilla.org/en-US/docs/Web/API/FileList
        var files  = this.files;
        // Let's create an empty `errors` String to collect eventual errors into:
        var errors = "";
      
        if (!files) {
          errors += "File upload not supported by your browser.";
        }
      
        // Check for `files` (FileList) support and if contains at least one file:
        if (files && files[0]) {
      
          // Iterate over every File object in the FileList array
          for(var i=0; i<files.length; i++) {
      
            // Let's refer to the current File as a `file` variable
            // https://developer.mozilla.org/en-US/docs/Web/API/File
            var file = files[i];
      
            // Test the `file.name` for a valid image extension:
            // (pipe `|` delimit more image extensions)
            // The regex can also be expressed like: /\.(png|jpe?g|gif)$/i
            if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
              // SUCCESS! It's an image!
              // Send our image `file` to our `readImage` function!
              readImage( file ); 
            } else {
              errors += file.name +" Unsupported Image extension\n";  
            }
          }
        }
      
        // Notify the user for any errors (i.e: try uploading a .txt file)
        if (errors) {
          alert(errors); 
        }
      
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-12
        • 1970-01-01
        • 2021-05-06
        • 1970-01-01
        • 2021-05-29
        • 2013-06-19
        相关资源
        最近更新 更多