Validate image by JavaScript

0

I want to validate the image through JavaScript where I want to validate the type of image (png, jpg, etc) and that the size is not greater than the one established.

At the moment I've done this:

document.querySelector("#imagen").addEventListener("change", function(){
    var file = this.files[0], image = new Image();
    if (/.(gif|jpeg|jpg|png)$/i.test(file.value))
    {
        alert('Comprueba la extensión de tus imagenes, recuerda que los formatos aceptados son .gif, .jpeg, .jpg y .png');
        document.getElementById("f1").focus();
        return false;
    }    
    image.src = URL.createObjectURL(file);
    image.addEventListener("load", function(){
        console.log("Ancho: " + this.width + "px");
        console.log("Alto: " + this.height + "px");
    }, false);
}, false);

Validation I want to do it by onchange .

    
asked by jorgnv 20.08.2017 в 18:38
source

3 answers

1

In my case, for some time now I have begun to consider certain strategic classes for my project. One of them is jquery form-validator that incorporates javascript validations through jquery for multiple uses in the html / php forms I perform.

For your request, in the case of images you can validate the type of image file, its size in px (minimum and maximum), its frame (high-width ratio), among many other things.

In the case of image validation you should only add the additional variables to the input field: data-validation-allowing="jpg" and data-validation-dimension="min100" to activate it. See example:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>

<form>
  <fieldset>

    <div class="form-group">
      <?php // campo IMAGEN NATURAL ?>
      <label for="img_natural" class="col-sm-6 control-label">Imagen Natural (N)</label>
      <div class="col-sm-10"><input type="file" id="img_natural" name="img_natural" accept="image/jpeg" data-validation-allowing="jpg" data-validation-error-msg="Elija una imagen con formato JPG." data-validation="required" />
        <p class="help-block">formato .JPG (requerido)</p>
      </div>
    </div>


    <div class="form-group">
      <?php // campo IMAGEN MINIATURA ?>
      <label for="img_miniatura" class="col-sm-6 control-label">Imagen Miniatura (M)</label>
      <div class="col-sm-10"><input type="file" id="img_miniatura" name="img_miniatura" accept="image/jpeg" data-validation-allowing="jpg" data-validation-error-msg="Elija una imagen con formato JPG." data-validation="required" />
        <p class="help-block">formato .JPG, tamaño 100 x 100 px</p>
      </div>
    </div>

    <button>Enviar</button>

  </fieldset>
</form>

<script>
  $.validate({
    modules: 'file'
  });
</script>

For the case of file sizes, you can include the variables in the input field:

data-validation="mime size" data-validation-allowing="jpg, png, gif" data-validation-max-size="2M

which will validate maximum size 2MB and format of the files to be imported.

It's simple. Surely you will ask yourself, why include classes? In my case the answer was that I'm only going to add classes that solve several problems at the same time. If it only solves a validation or a refill, it's not worth it. This class is worth it.

    
answered by 08.12.2017 в 00:35
0

Try this:

function openImage() { //Esta función validaría una imágen
        
      var input = this;
      var file = input.files[0];
      var fileName = input.value;
      var maxSize = 1048576; //bytes
      var extensions = new RegExp(/.jpg|.jpeg|.png/i); //Extensiones válidas

      var error = {
          state: false,
          msg: ''
      };

      if (this.files && file) {

          for (var i = fileName.length-1; i >= 0; i--) {

              if (fileName[i] == '.') {

                  var ext = fileName.substring(fileName[i],fileName.length);

                  if (!extensions.test(ext)) {
                      error.state = true;
                      error.msg+= 'La extensión del archivo no es válida.<br>';
                  }

                  break;
              }

          }

          if (file.size > maxSize) {
              error.state = true;
              error.msg += 'La imágen no puede ocupar más de '+maxSize/1048576+' MB.';
          }

          if (error.state) {
              input.value = '';
              document.getElementById("result").innerHTML = error.msg;
              return;
          } else {
            document.getElementById("result").innerHTML = "El archivo es válido";
          }
         
          var reader = new FileReader();

          reader.onload = function(e) {
              document.getElementById("img").src = e.target.result;
          }
          reader.readAsDataURL(this.files[0]);
        }
  }
    document.getElementById("file").addEventListener("change",openImage,false); //Añadimos un evento al input para que se dispare cuando el usuario seleccione otro archivo
/* Un poquito de CSS  ;) */

* {
  padding: 10px;
}

input[type=file] {
  display: none;
}

label {
  background: #FF5555;
  color: #fff;
  border-radius: 5px;
  padding: 10px;
  border: 1px solid #FF5555;
  cursor: pointer;
  margin-top: 5px;
  transition: ease 0.3s;
}

label:hover {
  background: #fff;
  color: #FF5555;
}

#result {
  display: inline-block;
  margin-top: 20px;
  background: #666;
  border-radius: 2px;
  color: #fff;
  box-shadow: 0px 0px 5px rgba(0,0,0,0.3);
}
<label for="file">Elegir archivo</label>
  <input id="file" type="file">
  <br>
<div id="result">Esperando archivo...</div>
  <br>
<img id="img">

I hope it helps.

    
answered by 20.08.2017 в 18:52
0

Take a look to see if this script can help you, by clicking on a button, you choose the image and if it is valid, it is shown on the page.

$(document).ready(function(){

	var extensionesValidas = ".png, .gif, .jpeg, .jpg";
	var pesoPermitido = 1024;

	// Cuando cambie #fichero
	$("#fichero").change(function () {

		$('#texto').text('');
		$('#img').attr('src', '');

		if(validarExtension(this)) {

		    if(validarPeso(this)) {

		    	verImagen(this);

		    }

		}  

	});

	// Validacion de extensiones permitidas

	function validarExtension(datos) {

		var ruta = datos.value;
		var extension = ruta.substring(ruta.lastIndexOf('.') + 1).toLowerCase();
		var extensionValida = extensionesValidas.indexOf(extension);

		if(extensionValida < 0) {

			 	$('#texto').text('La extensión no es válida Su fichero tiene de extensión: .'+ extension);
			 	return false;

			} else {

			  	return true;

		}

	}

	// Validacion de peso del fichero en kbs

	function validarPeso(datos) {

		if (datos.files && datos.files[0]) {

	        var pesoFichero = datos.files[0].size/1024;

	        if(pesoFichero > pesoPermitido) {

	            $('#texto').text('El peso maximo permitido del fichero es: ' + pesoPermitido + ' KBs Su fichero tiene: '+ pesoFichero +' KBs');
	            return false;

	        } else {

	            return true;

	        }

	    }

	}

	 // Vista preliminar de la imagen.
	function verImagen(datos) {

	    if (datos.files && datos.files[0]) {

	        var reader = new FileReader();

	        reader.onload = function (e) {

	            $('#img').attr('src', e.target.result);

	        };

	        reader.readAsDataURL(datos.files[0]);

	    }

	}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<input type='file' id="fichero" />

	<br/>

	<p id="texto"> </p>

	<br/>

	<img id="img" src="" />
    
answered by 30.08.2017 в 20:59