Html – ny way to resize a image before saving to Web SQL in HTML5

canvashtmlimagejqueryresize

I need to allow user to pick images and then save the base64 image data to web sql database in Chrome. Then at one point when user gets online, upload those data to server.

I can get the image data like this:

function onFileUploadChange(input) {
        if (input.files && input.files[0]) {
            //alert(input.files.length);
            for (i = 0; i < input.files.length; i++) {
                previewImage(input.files[i], "ImageTag" + getUniqueID());
            }
        }
    }

    function previewImage(file, imgID) {

        $("#ImagePreview").append("<img id='" + imgID + "'  />");

        var reader = new FileReader();
        reader.onload = function (e) {
            $("#" + imgID)
            .attr('src', e.target.result)
            .width(200)
            .height(200);

        };

        reader.readAsDataURL(file);
    }

the image.src has the base64 image data.

Once user clicks save, I will grab all images' src which is the base64 image data and save them to web sql database of chrome.
Now the problem is most pictures are too large. I want to resize them to say 1/4 of original size, then save it to web sql. Is there any way to do it? Probably with canvas?

Thanks.

Best Answer

Here's an example of doing it in canvas:

http://jsfiddle.net/7QMqX/

In case jsfiddle goes down, here's the relevant part:

img.onload = function() {
    // original image size:
    console.log(img.width); // 182
    console.log(img.height); // 176
    // lets resize it to 1/4 original size
    var bigside = Math.max(img.width, img.height);
    var ratio =  0.25;
    can.width = img.width * ratio;
    can.height = img.height* ratio;
    ctx.scale(ratio, ratio); // scale by 1/4
    ctx.drawImage(img, 0, 0);
    // Lets also show the original image for comparison:
    document.body.appendChild(img);

    // anyway, now we can use this command to get the base64 data of the resized image:
    console.log(can.toDataURL());
}

You can draw anything to canvas, and so you load the image, resize the canvas to be 1/4 the image's size, scale the canvas by 1/4, and then draw the image. Then you can get the bitmap on the canvas by calling toDataURL, which returns the base64 string.

note that toDataURL will fail if any of the items drawn to a canvas are not same-domain or cors-enabled.

Related Topic