【问题标题】:Is there any way to resize a image before saving to Web SQL in HTML5?有没有办法在 HTML5 中保存到 Web SQL 之前调整图像的大小?
【发布时间】:2012-06-07 17:16:48
【问题描述】:

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

谢谢。

【问题讨论】:

  • Imagemagick 通常用于这些类型的事情,但这是一种服务器端技术。
  • 不,我必须在客户端这样做,因为用户可能会在离线模式下挑选照片。

标签: jquery image html canvas resize


【解决方案1】:

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

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 将失败。

【讨论】:

  • 谁能展示我如何将它与用户通过输入类型文件选择的文件一起使用?
猜你喜欢
  • 2021-04-28
  • 2012-12-14
  • 2011-09-01
  • 1970-01-01
  • 2021-12-31
  • 2011-12-10
  • 1970-01-01
  • 2012-10-19
  • 2018-08-28
相关资源
最近更新 更多