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:
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.