有没有办法在HTML5中保存到Web SQL之前调整图像大小?

时间:2012-06-03 03:21:32

标签: jquery image html5 canvas resize

我需要允许用户选择图像,然后将base64图像数据保存到Chrome中的web sql数据库。然后,当用户上线时,将这些数据上传到服务器。

我可以像这样得到图像数据:

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);
    }

image.src具有base64图像数据。

一旦用户点击保存,我将获取所有图像的src,即base64图像数据,并将它们保存到chrome的web sql数据库中。 现在的问题是大多数图片都太大了。我想调整它们的大小来说原始大小的1/4,然后将其保存到web sql。有什么办法吗?可能用帆布?

感谢。

1 个答案:

答案 0 :(得分:7)

以下是在canvas中执行此操作的示例:

http://jsfiddle.net/7QMqX/

如果jsfiddle发生故障,这里是相关部分:

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());
}

您可以在画布上绘制任何内容,因此您加载图像,将画布调整为图像大小的1/4,将画布缩放1/4,然后绘制图像。然后,您可以通过调用toDataURL来获取画布上的位图,这将返回base64字符串。

请注意,如果绘制到画布的任何项目不是同域或cors-enabled,则toDataURL将失败。

相关问题