BetuUuUu

resizeImage

Nov 18th, 2013
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function resizeImage(f) {
  2.    
  3.     var file = f,
  4.         fileType = file.type,
  5.         reader = new FileReader();
  6.  
  7.     reader.onloadend = function() {
  8.       var image = new Image();
  9.           image.src = reader.result;
  10.          
  11.       image.onload = function() {
  12.         var maxWidth = 250,
  13.             maxHeight = 250,
  14.             imageWidth = image.width,
  15.             imageHeight = image.height;
  16.  
  17.         if (imageWidth > imageHeight) {
  18.           if (imageWidth > maxWidth) {
  19.             imageHeight *= maxWidth / imageWidth;
  20.             imageWidth = maxWidth;
  21.           }
  22.         }
  23.         else {
  24.           if (imageHeight > maxHeight) {
  25.             imageWidth *= maxHeight / imageHeight;
  26.             imageHeight = maxHeight;
  27.           }
  28.         }
  29.  
  30.         var canvas = document.createElement('canvas');
  31.         canvas.width = imageWidth;
  32.         canvas.height = imageHeight;
  33.  
  34.         var ctx = canvas.getContext("2d");
  35.         ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
  36.  
  37.         // The resized file ready for upload
  38.         finalFile = dataURItoBlob(canvas.toDataURL(fileType));
  39.       }
  40.     }
  41.     reader.readAsDataURL(file);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment