Avatar of Michael Vasilevsky
Michael VasilevskyFlag for United States of America asked on

How to Resize an Image on Upload with JavaScript

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]));

Open in new window

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>

Open in new window

JavaScript* canvas

Avatar of undefined
Last Comment
Michael Vasilevsky

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
leakim971

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Michael Vasilevsky

Perfect! Thank you
Your help has saved me hundreds of hours of internet surfing.
fblack61