troubleshooting Question

How to Resize an Image on Upload with JavaScript

Avatar of Michael Vasilevsky
Michael VasilevskyFlag for United States of America asked on
JavaScript* canvas
2 Comments1 Solution176 ViewsLast Modified:
I'm trying to resize a photo on upload using JavaScript but can't get it. I'm using the below code (also here). I want to resize any photo to a maximum size of 800x600.

The commented out
reader.readAsDataURL(resizeMe(input.files[0]));
is what I want to work:

<input id="getFile" type="file" accept="image/*"/>
<img class="pic" src="" />

<script>
var readURL = function(input) {
  if (input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
      $('.pic').attr('src', e.target.result);
    }
    
    reader.readAsDataURL(input.files[0]);
    //reader.readAsDataURL(resizeMe(input.files[0]));
    
  }
}

$("#getFile").on('change', function(){
  readURL(this);
});

function resizeMe(file) {
    var dataURL = "x";
    var reader = new FileReader();
    reader.onloadend = function () {

        var tempImg = new Image();
        tempImg.src = reader.result;
        tempImg.onload = function () {

            var MAX_WIDTH = 800;
            var MAX_HEIGHT = 600;
            var tempW = tempImg.width;
            var tempH = tempImg.height;
            if (tempW > tempH) {
                if (tempW > MAX_WIDTH) {
                    tempH *= MAX_WIDTH / tempW;
                    tempW = MAX_WIDTH;
                }
            } else {
                if (tempH > MAX_HEIGHT) {
                    tempW *= MAX_HEIGHT / tempH;
                    tempH = MAX_HEIGHT;
                }
            }

            var canvas = document.createElement('canvas');
            canvas.width = tempW;
            canvas.height = tempH;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(this, 0, 0, tempW, tempH);
            dataURL = canvas.toDataURL("image/jpeg");
        };

    };
    
    reader.readAsDataURL(file);

    return dataURL;
}
</script>
ASKER CERTIFIED SOLUTION
leakim971
Multitechnician
Join our community to see this answer!
Unlock 1 Answer and 2 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros