Resize Image Canvas

by mhctoledo

HTML

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

JavaScript

//Cargamos el objeto canvas
var thecanvas = document.getElementById("queImg");
var ctx       = thecanvas.getContext("2d");

var ImagenOriginal = new Image();

//Acciones tras cargar la imagen
ImagenOriginal.onload = function() { 
	var width = ImagenOriginal.width;
  var widthNatural = ImagenOriginal.naturalWidth;
  
  var height = ImagenOriginal.height;
  var heightNatural = ImagenOriginal.naturalHeight;
  
  //var r = gcd(width, height);
  
  var quality = 80;

  //document.write("Width:",width,"<br>");
  //document.write("Height:",height,"<br>");

  var maxWidth = 1024; // Max width for the image
  var maxHeight = 1024;    // Max height for the image
  var ratio = 0;  // Used for aspect ratio

	console.log(calculateAspectRatioFit(width,height,maxWidth,maxHeight));


  // 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
  }
  console.log(width);
  console.log(height);
  /*document.write("Ancho: ",ancho,"<br>");
  document.write("Ancho Natural: ",anchoNatural,"<br>");
  document.write("Alto: ",alto,"<br>");
  document.write("Alto Natural: ",altoNatural,"<br>");
  document.write('GCD-(Maximo comun divisor): ',r,"<br>");
  document.write("Aspect     = ", ancho/r, ":", alto/r,"<br>");*/
  var a = "image/png";
  var r = document.createElement("canvas");
  r.width = width;
  r.height = height;
  var o = (r.getContext("2d").drawImage(ImagenOriginal, 0, 0,width,height), r.toDataURL(a, quality / 100));
  var s = new Image;
  s.src = o, s;
  
  console.log(o);
  
...