【问题标题】:Implementation of resize jpeg image with javascript to a fixed size使用javascript将jpeg图像大小调整为固定大小的实现
【发布时间】:2016-02-11 20:42:24
【问题描述】:

这是我们在客户端将 jpeg 大小调整为 1024 或 768 的固定大小的实现。工作场景是用户选择他/她想要上传的图像(原始图像)(不显示)。如果原始图像的尺寸大于 1024 或 768,则按比例调整图像大小。下面的代码计算了 should-be 的宽高,并进行了resize。

有 2 个alert() 显示调整大小前后的图像大小。我们发现文件大小并没有减少。代码有什么问题?

$(function(){
    $('#uploaded_file_file_for_upload').change(function(){
        var _URL = window.URL || window.webkitURL;
        var img, img_width = 0, img_height = 0, max_width = 1024, max_height = 768;
        var f = $(this)[0].files[0];  
        alert(f.size);
        if (f.type == 'image/jpeg' || f.type == 'image/jpg') {
            img = new Image();
            img.onload = function () {
              img_width = this.width;  
              img_height = this.height;
            };
            img.src = _URL.createObjectURL(f);
            if (img_width > max_width){
                img_height = Math.ceil(img_height * max_width / img_width);
                img_width = max_width;
            } else if (img_height > max_height) {
                img_width = Math.ceil(img_width * max_height / img_height);
                img_height = max_height;
            };
            resize(img, img_width, img_height);
            var f1 = $(this)[0].files[0]; 
            alert(f1.size);
        };

        function resize(image, width, height) {
          var mainCanvas = document.createElement("canvas");
          mainCanvas.width = width;
          mainCanvas.height = height;
          var ctx = mainCanvas.getContext("2d");
          ctx.drawImage(image, 0, 0, width, height);
          $('#uploaded_file_file_for_upload').attr('src', mainCanvas.toDataURL("image/jpeg"));
        };

        return false;

    });
});

【问题讨论】:

  • 经过调试,我们已经验证了图片调整大小的工作。问题可以缩小到将调整大小的图像附加到元素 #uploaded_file_file_for_upload 是代码行 $('#uploaded_file_file_for_upload').attr('src', mainCanvas.toDataURL("image/jpeg"));跨度>

标签: javascript jquery image html5-canvas


【解决方案1】:

从图像中检查naturalWidth,而不是css width

【讨论】:

  • 图片宽度没有问题。
  • 请考虑编辑您的帖子,以添加更多关于您的代码的作用以及它为何能解决问题的说明。一个大部分只包含代码的答案(即使它正在工作)通常不会帮助 OP 理解他们的问题。如果只是猜测,还建议您不要发布答案。一个好的答案将有一个合理的理由说明它为什么可以解决 OP 的问题。
猜你喜欢
  • 2013-08-12
  • 2011-11-17
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
相关资源
最近更新 更多