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

use*_*138 4 jquery html5 resize canvas image

我需要允许用户选择图像,然后将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);
    }
Run Code Online (Sandbox Code Playgroud)

image.src具有base64图像数据.

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

谢谢.

Sim*_*ris 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());
}
Run Code Online (Sandbox Code Playgroud)

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

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