Home > Web Front-end > JS Tutorial > body text

How to Check Image Width and Height Before Upload with Javascript?

Susan Sarandon
Release: 2024-11-01 12:55:02
Original
1017 people have browsed it

How to Check Image Width and Height Before Upload with Javascript?

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;
$(&quot;#file&quot;).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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template