0

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; I'm using "this.width" and "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??
                        }
                    }
                });
            });
0

2 Answers 2

1

FileReader has not the properties width and height. You can use Image instead like following. 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>

Sign up to request clarification or add additional context in comments.

Comments

0

Try to save to a variables the width and height of the photo using this, right in the beginning of the first function, then, use those variables in the second function.. It's a scope issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.