Course contentsShow
← Web Development
Lesson 2700 of 2,98248. File Uploads and HandlingFree lesson

Image Dimension Validation

Load images into Image objects to check width and height before allowing upload.

Image Dimension Validation

What you'll learn: How to verify that uploaded images meet specific width and height requirements before processing them.

Why Validate Dimensions?

After checking file type and size, you often need to ensure images meet dimension requirements—perhaps profile pictures must be at least 200×200 pixels, or banners can't exceed 1920×1080. Unlike file size (which you can read directly from the File object), dimensions require loading the image data first.

The Core Technique

You'll use the browser's Image object (also called HTMLImageElement). Here's the approach:

  1. Create an Image instance
  2. Read the file as a Data URL using FileReader
  3. Assign the Data URL to the image's src
  4. Listen for the load event — only then can you access width and height
  5. Validate dimensions before proceeding with upload

Think of it like developing a photograph: you can't measure the picture until it's fully developed. The load event signals "development complete."

Example Pattern

function validateImageDimensions(file, minWidth, minHeight) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    const img = new Image();

    img.onload = () => {
      if (img.width >= minWidth && img.height >= minHeight) {
        resolve({ valid: true, width: img.width, height: img.height });
      } else {
        reject(`Image must be at least ${minWidth}×${minHeight}px`);
      }
    };

    reader.onload = (e) => {
      img.src = e.target.result; // Data URL triggers img.onload
    };

    reader.readAsDataURL(file);
  });
}

The FileReader converts the file to a Data URL, which the Image object can load. Once loaded, img.width and img.height become accessible for validation.

Key Takeaway: Image dimension validation requires creating an Image object, loading the file as a Data URL, and checking the width and height properties in the load event handler before allowing upload.