Search code examples
htmljquery-mobilehtml5-canvasblackberry-webworks

Image resize with HTML5 Canvas - Distortion


I'm working on a Webworks app where I need to resize an image for upload to a server. I'm using JQuery Mobile, the app needs to run on OS6 and up. The user can either use the camera or select an image off the device. The relevant code is as follows:

function handleOpenedFile(fullPath, blobData) {
            var image = new Image();
            image.src = fullPath; //path to image
            image.onload = function () {
                var resized = resizeMe(image); // send it to canvas
                //Do stuff with the DataURL returned from resizeMe()
            };
    }

function resizeMe(img) {

        var canvas = document.createElement('canvas');
        var width = Math.round(img.width / 2);
        var height = Math.round(img.height / 2);
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);
        return canvas.toDataURL("image/jpeg", 0.8);
    }

I then use the Base64 in the DataURL for uploading to the server. The images get scaled but they come out garbled. Parts of the image are shifted around and colours come out strange. It's not the scaling per se that messes up the image as it comes out garbled if you draw it on the canvas without any scaling.

I've searched both SO and the BB Dev forums extensively with no luck.

Does anyone have any idea how to fix this or have an alternative suggestion for resizing an image for upload?


Solution

  • I've managed to solve the problem although why it works eludes me. Simply replace

    return canvas.toDataURL("image/jpeg", 0.8);
    

    with

    return canvas.toDataURL();
    

    This returns a base64 encoded string with the properly resized image without any strange visual artifacts.