Resize Image Canvas

Convert image size loaded by input file

by mhctoledo

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<canvas id="queImg" ></canvas>
<input type='file' id="fichero" accept='image/*'>
<img id="output" />

JavaScript

var thecanvas = document.getElementById("queImg");
var ctx       = thecanvas.getContext("2d");

var ImagenOriginal = new Image();

//Tratamos la imagen cuando se carga
ImagenOriginal.onload = function() {
	var width = ImagenOriginal.naturalWidth;
  var height = ImagenOriginal.naturalHeight;
  
  //document.write("Ancho: ",width,"<br>");
  //document.write("Alto: ",height,"<br>");
  
  
  var quality = 80;
  var maxWidth = 1024; // Max width for the image
  var maxHeight = 1024;    // Max height for the image
  var ratio = 0;  // Used for aspect ratio
  
   // Check if the current width is larger than the max
  if (width > maxWidth){
      ratio = maxWidth / width;   // get ratio for scaling image
      height = height * ratio;    // Reset height to match scaled image
      width = width * ratio;    // Reset width to match scaled image
  }

  // Check if current height is larger than max
  if (height > maxHeight){
      ratio = maxHeight / height; // get ratio for scaling image
      width = width * ratio;    // Reset width to match scaled image
      height = height * ratio;    // Reset height to match scaled image
  }
  
	//document.write("Ancho: ",width,"<br>");
  //document.write("Alto: ",height,"<br>");
  
  var r = document.createElement("canvas");
  r.width = width;
  r.height = height;
  var o = r.getContext("2d").drawImage(ImagenOriginal, 0, 0,width,height); 
  var datos = r.toDataURL("image/jpeg", quality / 100);
  console.log(datos);

}

//Cargamos el fichero
$("#fichero").change(function(event){
	var input = event.target;
  var reader = new FileReader();
  reader.onload = function(){
  	var dataURL = reader.result;
    ImagenOriginal.src = dataURL;
	};
  reader.readAsDataURL(input.files[0]);
});