Resizing image client side and uploading via AJAX only works sometimes

I’m having an issue with code to allow a user to submit an image file via a form, resize it client side, upload it via AJAX and PHP to a WordPress site, and then showing a thumbnail version of the image. The problem is the code only works sometimes and it seems to prefer some files over others. I have one jpeg image that only uploads maybe once out of every 10 attempts and other jpeg images that upload 5 out of 10 times. Also, when an image is uploading and reaches 100%, sometimes the progress bar will go back down to about 85% and then go up to 100% again. I’m thinking this is the cause of my issue, but I haven’t been able to figure out how to fix it.

jQuery:

$('#myform-fileinput').change(function() { 
    if ($('#myform-fileinput').length) {

        if (window.File && window.FileReader && window.FileList && window.Blob) {

            var filesToUpload = document.getElementById('myform').files;
            var file = filesToUpload[0];

            var img = document.createElement("img");
            var reader = new FileReader();
            reader.onload = function(e)
            {
                img.src = e.target.result;

                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);
                // Do other manipulations and send via AJAX here
            reader.readAsDataURL(file);
        }
    }
});

Related posts

1 comment

  1. I was able to solve the issue, which turned out to be very simple. In the code, instead of doing

    reader.onload = function(e)
            {
                img.src = e.target.result;
    
                var canvas = document.createElement("canvas");
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);
                // Do other manipulations and send via AJAX here
            }
    reader.readAsDataURL(file);
    

    I needed to do

    reader.onload = function(e)
            {
                image.onload = function () {
                   var canvas = document.createElement("canvas");
                   var ctx = canvas.getContext("2d");
                   ctx.drawImage(img, 0, 0);
                   // Do other manipulations and send via AJAX here
                }
    
                image.src = e.target.result;
            }
    reader.readAsDataURL(file);
    

    I just needed to give time for the image data to load prior to manipulating it.

Comments are closed.