Verifique el ancho y alto de la imagen antes de subirla con Javascript


122

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 este 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 verificar el tipo y tamaño de archivo. Ahora quiero comprobar el ancho y el alto de la imagen, pero no puedo hacerlo.
Lo he intentado target.files[0].widthpero lo consigo undefined. Con otras formas lo consigo 0.
¿Alguna sugerencia?

Respuestas:


221

El archivo es solo un archivo, necesita crear una imagen como esta:

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 () {
            alert(this.width + " " + this.height);
            _URL.revokeObjectURL(objectUrl);
        };
        img.src = objectUrl;
    }
});

Manifestación: http://jsfiddle.net/4N6D9/1/

Supongo que se da cuenta de que esto solo es compatible con algunos navegadores. En su mayoría Firefox y Chrome, también podría ser Opera a estas alturas.

PD: El método URL.createObjectURL () se ha eliminado de la interfaz de MediaStream. Este método quedó en desuso en 2013 y se reemplazó al asignar secuencias a HTMLMediaElement.srcObject. El método anterior se eliminó porque es menos seguro y requiere una llamada a URL.revokeOjbectURL () para finalizar la transmisión. Otros agentes de usuario han desaprobado (Firefox) o eliminado (Safari) esta característica.

Para obtener más información, consulte aquí .


1
definitivamente no funcionará en safari a menos que tenga safari 6.0. 6.0 es la única versión que admite la API de archivos a partir de ahora. Y no creo que Apple alguna vez lance 6.0 para Windows. 5.1.7 han sido la última versión de safari de hace mucho tiempo
Seho Lee

Funciona en IE10, pero no parece funcionar en IE9 y por debajo. Y eso se debe a que IE9 y versiones anteriores no admiten la API de archivos ( caniuse.com/#search=file%20api )
Michael Yagudaev

28

En mi opinión, la respuesta perfecta que debe solicitar 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;
};

18

Estoy de acuerdo. Una vez que se carga en un lugar al que el navegador del usuario puede acceder, es bastante fácil obtener el tamaño. Como necesita esperar a que se cargue la imagen, querrá conectarse al onloadevento 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";

7

Esta es la forma más sencilla de comprobar el tamaño.

let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
   alert(img.width + " " + img.height);
}

Verifique el tamaño específico. Usando 100 x 100 como ejemplo

let img = new Image()
img.src = window.URL.createObjectURL(event.target.files[0])
img.onload = () => {
   if(img.width === 100 && img.height === 100){
        alert(`Nice, image is the right size. It can be uploaded`)
        // upload logic here
        } else {
        alert(`Sorry, this image doesn't look like the size we wanted. It's 
   ${img.width} x ${img.height} but we require 100 x 100 size image.`);
   }                
}

2

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;
        }
    }

1
Intente formatear el código completo y proporcione una pequeña descripción de lo que hizo en su código.
Zeeshan Adil

2

Adjunte la función al método onchange del tipo de entrada file / onchange = "validateimg (this)" /

   function validateimg(ctrl) { 
        var fileUpload = ctrl;
        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;
                        if (height < 1100 || width < 750) {
                            alert("At least you can upload a 1100*750 photo size.");
                            return false;
                        }else{
                            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

    const ValidateImg = (file) =>{
        let img = new Image()
        img.src = window.URL.createObjectURL(file)
        img.onload = () => {
            if(img.width === 100 && img.height ===100){
                alert("Correct size");
                return true;
            }
            alert("Incorrect size");
            return true;
        }
    }


-1
function 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.");
        }

    }

¡Bienvenido a Stack Overflow! Por favor, no responda solo con el código fuente. Intente proporcionar una descripción agradable sobre cómo funciona su solución. Ver: ¿Cómo escribo una buena respuesta? . Gracias
sɐunıɔ ןɐ qɐp
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.