4

我需要允许用户选择图像,然后将 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。有什么办法吗?应该是帆布吧?

谢谢。

4

1 回答 1

7

这是在画布中执行此操作的示例:

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

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.

于 2012-06-03T03:57:40.683 回答