简体   繁体   English

使用jQuery FileReader获得宽度和高度?

[英]Using jQuery FileReader to get width and height?

I'm using jQuery to show an image in a div (#image-preview) when an image is selected, and I can't figure out how to get the width and the height of the image; 选择图像后,我正在使用jQuery在div(#image-preview)中显示图像,但我不知道如何获取图像的宽度和高度。 I'm using "this.width" and "this.height". 我正在使用“ this.width”和“ this.height”。

Here is my code: 这是我的代码:

$(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??
                        }
                    }
                });
            });

FileReader has not the properties width and height. FileReader没有属性width和height。 You can use Image instead like following. 您可以使用Image代替,如下所示。 Hope this will help you. 希望这会帮助你。

 $('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> 

尝试在第一个功能的开头使用此功能将照片的宽度和高度保存为变量,然后在第二个功能中使用这些变量。这是范围问题。

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

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