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:
- Create an
Imageinstance - Read the file as a Data URL using
FileReader - Assign the Data URL to the image's
src - Listen for the
loadevent — only then can you accesswidthandheight - 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.