Resizing the client side of the image and loading via AJAX only works sometimes

I am having a problem with code that allows a user to submit an image file via a form, resize the client side, upload it via AJAX and PHP to a Wordpress site, and then display 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 downloads once out of every 10 attempts and other jpeg images that download 5 out of 10 times. Also, when the image is loaded and reaches 100%, sometimes the progress bar goes back to around 85% and then goes back to 100% again. I think this is the cause of my problem, 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);
        }
    }
});

      

+3


source to share


1 answer


I was able to solve the problem which turned out to be very simple. In 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 allow time to load the image data before manipulating it.

0


source







All Articles