How To Get Original Image Size (Width & Height) In JavaScript
Có thể bạn quan tâm
Topic: JavaScript / jQueryPrev|Next
Answer: Use the HTML5 naturalWidth and naturalHeight
You can easily find the original or intrinsic width and heigh of an image using the HTML5 image naturalWidth and naturalHeight properties. These properties are supported in all major web browsers such as Chrome, Firefox, Safari, Opera, Internet Explorer 9 and above.
Let's take a look at an example to understand how it basically works:
Example
Try this code » <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Find Real Image Width and Height</title> <script> function imgSize(){ var myImg = document.querySelector("#sky"); var realWidth = myImg.naturalWidth; var realHeight = myImg.naturalHeight; alert("Original width=" + realWidth + ", " + "Original height=" + realHeight); } </script> </head> <body> <img src="sky.jpg" id="sky" width="250" alt="Cloudy Sky"> <p><button type="button" onclick="imgSize();">Get Original Image Size</button></p> </body> </html>Alternatively, if you want to perform the same task with jQuery you can use the load() method in combination with the attr() method, as shown in the following example:
Example
Try this code » <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery Get Real Image Dimensions</title> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ var img = $("#sky"); // Create dummy image to get real width and height $("<img>").attr("src", $(img).attr("src")).load(function(){ var realWidth = this.width; var realHeight = this.height; alert("Original width=" + realWidth + ", " + "Original height=" + realHeight); }); }); }); </script> </head> <body> <img src="sky.jpg" id="sky" width="250" alt="Cloudy Sky"> <p><button type="button">Get Original Image Size</button></p> </body> </html>Related FAQ
Here are some more FAQ related to this topic:
- How to get current image size in JavaScript
- How to increase and decrease image size using JavaScript
- How to change the image source using jQuery
Từ khóa » Html Keep Original Image Size
-
Css - Keep Image Original Size Inside Smaller Div - Stack Overflow
-
How To Keep Dimensions Css Image Code Example - Code Grepper
-
How To Resize An Image In HTML?
-
How To Resize An Image With HTML - Computer Hope
-
Setting Height And Width On Images Is Important Again
-
Object-fit | CSS-Tricks
-
How To Fill A Box With An Image Without Distorting It - MDN Web Docs
-
Set The Height And Width Of An Image Using Percent - Tryit Editor V3.7
-
Resize Images Proportionally While Keeping The Aspect Ratio
-
C37: Using CSS Max-width And Height To Fit Images
-
Advanced Cropping, Resizing, And Resampling - Adobe Support
-
Photoshop Image Size And Resolution - Adobe Support
-
Preserve An Image's Aspect Ratio When Resized
-
HTML Tag: Change The Width Of A Picture In HTML »