代码之家  ›  专栏  ›  技术社区  ›  Houy Narun

按输入的百分比值调整图像文件大小?

  •  0
  • Houy Narun  · 技术社区  · 6 年前

    我试图编写脚本来按给定的百分比值调整图像文件的大小。我的脚本如下:

    let canvas;
    let array_WH = new Array();
    let percent = 50;
    let img = new Image();
    
    $(function() {
    
      function ff(height, width, percentage) {
    
        var newHeight = height * (percentage / 100);
    
        var newWidth = width * (percentage / 100);
    
        return [newWidth, newHeight];
      }
    
      $("#file_select").change(function(e) {
    
        var fileReader = new FileReader();
    
        fileReader.onload = function(e) {
    
    
    
          img.onload = function() {
    
            array_WH = ff(img.width, img.height, percent);
    
            console.log('old width: ' + img.width);
            console.log('new width: ' + array_WH[0]);
    
            width = array_WH[0];
    
            height = array_WH[1];
    
            if (canvas) return;
    
            canvas = document.createElement("canvas");
    
            canvas.width = width;
    
            canvas.height = height;
    
            canvas.getContext("2d").drawImage(this, 0, 0, width, height);
    
            // //Line added
            var canvasData = canvas.toDataURL();
            // //Line edited
            this.src = canvasData;
            // //Line added
            console.log(canvasData.length * 3 / 4, ' bytes');
    
            document.body.appendChild(this); //remove this if you don't want to show it
    
          }
    
          img.src = e.target.result;
    
        }
    
        fileReader.readAsDataURL(e.target.files[0]);
    
      });
    
    });
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>
    
    <h1 class="logo">Upload Picture</h1>
    <div id="upload_form_div">
      <form id="upload_form" method="POST" enctype="multipart/form-data" action="upload">
        <input type="file" name="file" capture="camera" id="file_select" />
      </form>
    </div>
    
    <div id="loading" style="display:none;">
      Uploading your picture...
    </div>

    你可以 FiddleJs 在这里演示。

    假设百分比是50%,因此 function ff(height, width, percentage) {...} 假定返回新宽度旧宽度的一半,新高度旧高度的一半,因此,返回旧图像大小的一半。

    但是,它并不能像预期的那样工作。我通过上传3.00MB(宽58000px,高3867px)的图像文件进行了测试,然后函数生成了9.5MB(宽1933px,高2900px)的新图像文件,这与1.5MB旧图像大小的一半的正确文件大小相差甚远。

    如何更正函数以达到给定百分比的预期结果?谢谢。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Pavel Ivanov    6 年前

    1)在FF呼叫中更改订单

    array_WH = ff(img.height, img.width, percent);
    

    2)添加参数:键入“image/jpeg”和jpeg 0.5的质量

    var canvasData = canvas.toDataURL('image/jpeg', 0.5)
    

    这是编辑好的小提琴 http://jsfiddle.net/2pu4tmkr/