How to useHTML “naturalWidth” and “naturalHeight” Attributes in Javascript
In this approach, we are extracting and displaying the dimensions or height and width of the uploaded image by the user using the HTML “naturalWidth” and “naturalHeight” attributes. In JavaScript code, the img,natrualWidth, and img.naturalHeughr are used to get the dimensions of the image, and these values are updated in the DOM element to show the dimensions of the loaded image when the button is been clicked.
Example: In this example, same as Approach 1, we are inputting the image from the user and there is a button once clicked by the user, the dimensions of the image are shown in the textual form rather than an alert box like approach 1.
HTML
<!DOCTYPE html> < html > < head > < title >w3wiki</ title > </ head > < body > < h1 style = "color: green;" >w3wiki</ h1 > < h3 > Approach 2: Using HTML "naturalWidth" and "naturalHeight" Attributes </ h3 > < input type = "file" id = "imageInput" accept = "image/*" > < div id = "dimensionsDiv" style = "display: none;" > < div style="width: 200px; height: 200px; overflow: hidden;"> < img id = "image" src = "" alt = "Sample Image" width = "200" height = "200" > </ div > < p > Image Dimensions: < span id = "dimensions" > </ span > </ p > </ div > < button id = "getDimensionsButton" > Get Dimensions </ button > < script src = "./script.js" ></ script > </ body > </ html > |
Javascript
let imgInput = document.getElementById( 'imageInput' ); let dimDiv = document.getElementById( 'dimensionsDiv' ); let dimSpan = document.getElementById( 'dimensions' ); let img = document.getElementById( 'image' ); let btn = document.getElementById( 'getDimensionsButton' ); // click event listener btn.addEventListener( 'click' , () => { let file = imgInput.files[0]; if (file) { let url = URL.createObjectURL(file); img.src = url; img.onload = () => { URL.revokeObjectURL(url); let width = img.naturalWidth; let height = img.naturalHeight; dimSpan.textContent = `${width} x ${height} pixels`; dimDiv.style.display = 'block' ; }; } else { dimDiv.style.display = 'none' ; alert( 'No image selected.' ); } }); |
Output:
JavaScript Program to Get the Dimensions of an Image
In this article, we need to retrieve the dimensions of an Image. The dimension of the image is nothing but the height and width of the image. This task is to be performed using JavaScript language. As it is a completely interactive statement, we will use HTML and CSS to make the application GUI-based for better understanding and concept understanding.
We can get the dimensions of an image in JavaScript using two different approaches:
Table of Content
- Using ‘width’ and ‘height’ properties in JavaScript
- Using HTML “naturalWidth” and “naturalHeight” Attributes
So, let’s see each of the approaches with its implementation in terms of examples.