【问题标题】:Using jQuery FileReader to get width and height?使用 jQuery FileReader 获取宽度和高度?
【发布时间】:2016-03-25 19:48:22
【问题描述】:

我正在使用jquery在选择图像时在div(#图像预览)中显示图像,并且我无法弄清楚如何获得宽度和图像的高度;我正在使用“this.width”和“this.height”。

这是我的代码:

$(document).ready(function() {
                $('input#photo').on('change', function() {
                    var files = !!this.files ? this.files : [];
                    if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
                    if (/^image/.test(files[0].type)) {  // only image file
                        var reader = new FileReader();   // instance of the FileReader
                        reader.readAsDataURL(files[0]);  // read the local file
                        reader.onloadend = function() {  
                            $('div#image-preview').css('display', 'inline-block');
                            $('div#image-preview').css('background-image', 'url(' + this.result + ')'); // set image data as background of div
                            $('div#image-preview').css('width', this.width); // doesn't work??
                            $('div#image-preview').css('height', this.height); // doesn't work??
                        }
                    }
                });
            });

【问题讨论】:

    标签: javascript jquery filereader


    【解决方案1】:

    尝试使用 this 将照片的宽度和高度保存到变量中,就在第一个函数的开头,然后,在第二个函数中使用这些变量。这是范围问题。

    【讨论】:

      【解决方案2】:

      FileReader 没有属性宽度和高度。您可以使用Image 来代替,如下所示。希望这会对你有所帮助。

      $('input#photo').on('change', function () {
            var files = !!this.files ? this.files : [], _URL = window.URL || window.webkitURL;
            if (!files.length) return;
      
            if (/^image/.test(files[0].type)) { 
               var img = new Image();
               img.onload = function () {
                    $('div#image-preview').css('display', 'inline-block');
                    $('div#image-preview').css('background-image', 'url(' + this.src + ')');
                    $('div#image-preview').css('width', this.width);
                    $('div#image-preview').css('height', this.height);
               };
               img.src = _URL.createObjectURL(files[0]);
            }
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <input type="file" id="photo"/>
      <div id="image-preview"></div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-06
        • 2012-04-04
        • 1970-01-01
        • 1970-01-01
        • 2017-02-28
        • 2014-08-01
        • 2017-12-26
        • 1970-01-01
        相关资源
        最近更新 更多