• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 52
  • Last Modified:

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

0
Michael Vasilevsky
Asked:
Michael Vasilevsky
1 Solution
 
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
 
Michael VasilevskySolutions ArchitectAuthor Commented:
Perfect! Thank you
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now