Compruebe el ancho y la altura de la imagen antes de cargarla con Javascript


Tengo un JPS con un formulario en el que un usuario puede poner una imagen:

<div class="photo">
    <div>Photo (max 240x240 and 100 kb):</div>
    <input type="file" name="photo" id="photoInput" onchange="checkPhoto(this)"/>
</div>

He escrito esto js:

function checkPhoto(target) {
    if(target.files[0].type.indexOf("image") == -1) {
        document.getElementById("photoLabel").innerHTML = "File not supported";
        return false;
    }
    if(target.files[0].size > 102400) {
        document.getElementById("photoLabel").innerHTML = "Image too big (max 100kb)";
        return false;
    }
    document.getElementById("photoLabel").innerHTML = "";
    return true;
}

Que funciona bien para comprobar el tipo y el tamaño del archivo. Ahora quiero comprobar el ancho y la altura de la imagen, pero no puedo hacerlo.
He intentado con target.files[0].width pero consigo undefined. Con otras formas obtengo 0.
Alguna sugerencia?

Author: SandroMarques, 2012-01-18

5 answers

El archivo es solo un archivo, necesita crear una imagen así:

var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            alert(this.width + " " + this.height);
        };
        img.src = _URL.createObjectURL(file);
    }
});

Demo: http://jsfiddle.net/4N6D9/1 /

Supongo que te das cuenta de que esto solo es compatible con unos pocos navegadores. En su mayoría firefox y Chrome, podría ser opera, así por ahora.

 174
Author: Esailija,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-18 01:33:29

Estoy de acuerdo. Una vez que se carga en algún lugar al que el navegador del usuario puede acceder, es bastante fácil obtener el tamaño. Como necesita esperar a que la imagen se cargue, querrá engancharse al evento onload para img.

var width, height;

var img = document.createElement("img");
img.onload = function() {
    // `naturalWidth`/`naturalHeight` aren't supported on <IE9. Fallback to normal width/height
    // The natural size is the actual image size regardless of rendering.
    // The 'normal' width/height are for the **rendered** size.

    width  = img.naturalWidth  || img.width;
    height = img.naturalHeight || img.height; 

    // Do something with the width and height
}

// Setting the source makes it start downloading and eventually call `onload`
img.src = "http://your.website.com/userUploadedImage.jpg";
 14
Author: pseudosavant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-21 23:37:34

En mi opinión, la respuesta perfecta que debe requerir es

 var reader = new FileReader();
    //Read the contents of Image File.
    reader.readAsDataURL(fileUpload.files[0]);
    reader.onload = function (e) {
    //Initiate the JavaScript Image object.
    var image = new Image();

    //Set the Base64 string return from FileReader as source.
                       image.src = e.target.result;

                        //Validate the File Height and Width.
                        image.onload = function () {
                            var height = this.height;
                            var width = this.width;
                            if (height > 100 || width > 100) {
                                alert("Height and Width must not exceed 100px.");
                                return false;
                            }
                            alert("Uploaded image has valid Height and Width.");
                            return true;
                        };

                    }
 8
Author: ash das,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-13 06:04:34

Función uploadfile (ctrl) { var validate = validateimg (ctrl);

        if (validate) {
            if (window.FormData !== undefined) {
                ShowLoading();
                var fileUpload = $(ctrl).get(0);
                var files = fileUpload.files;


                var fileData = new FormData();


                for (var i = 0; i < files.length; i++) {
                    fileData.append(files[i].name, files[i]);
                }


                fileData.append('username', 'Wishes');

                $.ajax({
                    url: 'UploadWishesFiles',
                    type: "POST",
                    contentType: false, 
                    processData: false, 
                    data: fileData,
                    success: function (result) {
                        var id = $(ctrl).attr('id');
                        $('#' + id.replace('txt', 'hdn')).val(result);

                        $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                        HideLoading();
                    },
                    error: function (err) {
                        alert(err.statusText);
                        HideLoading();
                    }
                });
            } else {
                alert("FormData is not supported.");
            }

        }
 0
Author: Shahbaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-11 09:43:52

Function validateimg (ctrl) {

        var fileUpload = $("#txtPostImg")[0];


        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
        if (regex.test(fileUpload.value.toLowerCase())) {

            if (typeof (fileUpload.files) != "undefined") {

                var reader = new FileReader();

                reader.readAsDataURL(fileUpload.files[0]);
                reader.onload = function (e) {

                    var image = new Image();

                    image.src = e.target.result;
                    image.onload = function () {

                        var height = this.height;
                        var width = this.width;
                        console.log(this);
                        if ((height >= 1024 || height <= 1100) && (width >= 750 || width <= 800)) {
                            alert("Height and Width must not exceed 1100*800.");
                            return false;
                        }
                        alert("Uploaded image has valid Height and Width.");
                        return true;
                    };
                }
            } else {
                alert("This browser does not support HTML5.");
                return false;
            }
        } else {
            alert("Please select a valid Image file.");
            return false;
        }
    }
 0
Author: Shahbaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-11 09:47:29