Explain Codes LogoExplain Codes Logo

How to get the image size (height & width) using JavaScript

javascript
image-api
image-dimensions
javascript-optimization
Nikita BarsukovbyNikita Barsukov·Dec 19, 2024
TLDR

Here's the quickest way to get an image's dimensions using JavaScript and its Image object:

const img = new Image(); img.onload = () => console.log(`Width: ${img.width}, Height: ${img.height}`); // Voilà, magic! img.src = 'image.jpg'; // Swap with your URL, obviously

It's as simple as setting the src attribute and accessing img.width and img.height once the image loads.

Choosing the right method

Different use cases, different methods. Let's break down your options:

  • In the DOM? Use properties like img.clientWidth, img.clientHeight, img.naturalHeight, and img.naturalWidth for the rendered and actual dimensions.
  • Using jQuery? Use the load() function and then $(this).height() and $(this).width().
  • Dynamic image? Use the Image object and the onload method, as demonstrated above.

Making the right method choice keeps your code efficient and the returned dimensions accurate.

Tackling image load timing

Ever had a surprise party ruined because someone arrived early? That's what trying to get dimensions of unloaded images feels like. Ensure your code runs after the document and images are fully loaded:

window.onload = () => { // Think of this as the "Surprise!" moment for your dimensions. };

This prevents dimension-retrieval attempts from stumbling over asynchronous loading hurdles.

As surprising as it might sound, not all browsers follow the "one for all, all for one" motto. Validate your code across all modern browsers to ensure an consistent outcome:

Meticulous with performance

Determine the runtime efficiency for each method - image dimension fetching can be an expensive operation, especially if you're running a photo gallery instead of just one image. Optimization and caching are your allies here.

New kid on the block: HTML5 image API

For those who appreciate the latest and greatest, the HTML5 image API offers advanced options to retrieve image dimensions. Remember to check for browser compatibility before incorporating it.

Checking dimensions pre-flight

Need to verify if an image suits your requirements before it lands on the screen? The JavaScript FileReader API might just be the ticket:

document.querySelector('input[type="file"]').addEventListener('change', event => { const file = event.target.files[0]; const reader = new FileReader(); reader.onload = (e) => { const img = new Image(); img.onload = () => console.log(`Width: ${img.width}, Height: ${img.height}`); img.src = e.target.result; }; reader.readAsDataURL(file); });

Balancing performance and user experience is critical here, lest you turn a speed-check into a roadblock!

Error handling: More than just a catch

Any good magician has a backup trick. Attach an onerror event to the Image object to perform in case of a failed loading:

img.onerror = () => { console.log('Oops! Image slipped through the cracks.'); };

This prevents your audience (users) from facing an abrupt end to the show and maintains a smooth experience.

The CSS safety net

In instances where JavaScript might be out of reach, CSS can step in to maintain visual harmony by setting image dimensions explicitly:

img { max-width: 100%; max-height: 100%; }

This won't report back to your JavaScript code, but it ensures your layout doesn't jump off the stage.