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

LVL 11
Michael VasilevskySolutions ArchitectAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
Go for that :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input id="getFile" type="file" accept="image/*"/>
<br/>
<img class="pic" src="" />

<script>
    var readURL = function(input) {
        if (input.files[0]) {
            var p = resizeMe(input.files[0]);
            p.then(function(imgBase64) {
                $('.pic').attr('src', imgBase64);
            }).catch(function(err){
                alert("error :\n" + err);
            });
        }
    }

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

    function resizeMe(file) {
        return new Promise(function(resolve, reject) {
            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");
                    resolve(dataURL);
                };
                tempImg.onerror = function(err) {
                    reject("can't load the image");
                }

            };
            reader.readAsDataURL(file);
        });
    }
</script>
</body>
</html>

Open in new window


Note : doesn't work on IE : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
but you can use two parts code (do part1 and call part2 when it's done) or use a plugin like bluebirdjs for example

1200x800800x553
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Michael VasilevskySolutions ArchitectAuthor Commented:
Perfect! Thank you
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.