Verifying Image Dimensions for Upload with Javascript
When implementing image upload forms in Javascript, ensuring that the uploaded images meet specific size requirements is essential. This article explores a common problem faced during image size validation: retrieving the width and height of the selected image.
The Problem
The following Javascript function, designed to check file type and size, fails to retrieve image dimensions:
<code class="javascript">function checkPhoto(target) { if(target.files[0].type.indexOf("image") == -1) { // Code to handle file type } if(target.files[0].size > 102400) { // Code to handle image size } // No code yet for image width and height }</code>
The Solution
To retrieve image dimensions, we need to create an image object from the selected file. This can be achieved using the URL.createObjectURL() method:
<code class="javascript">var _URL = window.URL || window.webkitURL; $(function() { $("#file").change(function (e) { var file, img; if ((file = this.files[0])) { img = new Image(); var objectUrl = _URL.createObjectURL(file); img.onload = function () { console.log(this.width + " " + this.height); _URL.revokeObjectURL(objectUrl); }; img.src = objectUrl; } }); });</code>
This code snippet creates an Image object and loads the selected file using img.src. Once the image is loaded, the callback function img.onload is executed, where we can access the image's width and height.
Compatibility Note
The URL.createObjectURL() method is not universally supported across browsers. It is primarily supported in Firefox and Chrome. For other browsers, alternative methods may be required for image size validation.
The above is the detailed content of How to Retrieve Image Dimensions for Upload Validation in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!