Check Image Width and Height Before Upload with Javascript
Before users can upload an image to a web application, it's essential to validate its dimensions to ensure compatibility with the desired display requirements. This Javascript code provides a solution to check image width and height before allowing the file to be submitted:
<code class="javascript">var _URL = window.URL || window.webkitURL; $("#file").change(function (e) { var file, img; if ((file = this.files[0])) { img = new Image(); var objectUrl = _URL.createObjectURL(file); img.onload = function () { if (this.width < 240 || this.height < 240) { alert("Image too small (min 240x240)"); } else { // Validation passed // Proceed with upload } _URL.revokeObjectURL(objectUrl); }; img.src = objectUrl; } });</code>
This code creates an image object from the file chosen by the user. The image object's "onload" event is used to obtain the width and height, which are then compared against the desired minimum dimensions. If the image meets the criteria, the validation passes, allowing the upload to proceed. Otherwise, an alert is displayed, informing the user that the image is too small.
Note: It's important to consider that some browsers, such as Safari, may not support the URL.createObjectURL() method. For cross-browser compatibility, alternative methods should be explored if necessary.
The above is the detailed content of How to Check Image Width and Height Before Upload with Javascript?. For more information, please follow other related articles on the PHP Chinese website!