Roman
Roman

Reputation: 3941

Javascript resize image before upload - read from canvas - image there, width and height 0

I am currently trying to resize images before the upload and to achieve this I am using JS/Jquery, has to be client side. On my server I simply deny all requests which are bigger then 30MB.

I am using this code:

    $( "input[type='file']" ).change(function() {

        console.log("function works");

        // from an input element
        var filesToUpload = this.files;
        console.log(filesToUpload);

        var img = document.createElement("img");
        img.src = window.URL.createObjectURL(this.files[0]);

        console.log("image: ", img);
        console.log("the image is: ", img.width);

        var MAX_WIDTH = 800;
        var MAX_HEIGHT = 600;
        var width = img.width;
        var height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }

        canvas = $("#uploading_canvas").get(0);;

        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);

        var dataurl = canvas[0].toDataURL("image/png");

        //var file = canvas.mozGetAsFile("foo.png");
    });

The first console.log output shows that the image is there, but somehow it has no width or height. Uploading an image with this code doesnt change anything atm.

Here are the console log outputs:

enter image description here

DataToUrl is undefined because the image is missing?

Upvotes: 0

Views: 1543

Answers (1)

Roman
Roman

Reputation: 3941

As @ymz explained in the comments the image needs time to load, so wrapping the image related code into an additional onload function solved the issue.

The solution looks like this:

        $( img ).load(function() {

            canvas = $("#uploading_canvas").get(0);


            var MAX_WIDTH = 600;
            var MAX_HEIGHT = 450;
            var width = img.width;
            var height = img.height;

            if (width > height) {
              if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
              }
            } else {
              if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
              }
            }       

            canvas.width = width;
            canvas.height = height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, width, height);

            var dataurl = canvas.toDataURL("image/png");

         });

Upvotes: 2

Related Questions