javascript 使用javascript调整图像大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27122713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:58:38  来源:igfitidea点击:

resize image using javascript

javascripthtml

提问by Saranga

I'm using javascript function to input image.

我正在使用 javascript 函数输入图像。

This is my HTML:

这是我的 HTML:

<input type="file" name="filUpload" id="filUpload" onclick="" onchange="showimagepreview(this)">
<br />
<div id="before">
<img id="imgprvw" alt="" class="img-thumbnail" style="width: 250px; height: 250px;" />

And this is my JavaScript:

这是我的 JavaScript:

function showimagepreview(input) { //image preview after select image
  if (input.files && input.files[0]) {
    var filerdr = new FileReader();
    filerdr.onload = function(e) {
      url = e.target.result;
      image = url;
      $('#imgprvw').attr('src', url);
      //console.log(url);

      //$('#imgprvw').attr('src', e.target.result);
      //url = e.target.result;
      //$("#imgpath").val(url);
    }
    filerdr.readAsDataURL(input.files[0]);
  }
}

This code convert image to bite array, I need to resize my image using that bite array. Is there any possible methods to do it.

此代码将图像转换为位数组,我需要使用该位数组调整图像大小。有没有可能的方法来做到这一点。

I will pass that binary array to web service. I the image size too high, it takes much time, that's why I need to convert.

我会将该二进制数组传递给 Web 服务。我的图像尺寸太大,需要很多时间,这就是我需要转换的原因。

采纳答案by nils

Resize it on the canvas like this:

像这样在画布上调整它的大小:

function showimagepreview(input) { //image preview after select image
  if (input.files && input.files[0]) {
    var filerdr = new FileReader();

    filerdr.onload = function(e) {
      var img = new Image();

      img.onload = function() {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        canvas.width = 250;
        canvas.height = canvas.width * (img.height / img.width);
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

        // SEND THIS DATA TO WHEREVER YOU NEED IT
        var data = canvas.toDataURL('image/png');

        $('#imgprvw').attr('src', img.src);
        //$('#imgprvw').attr('src', data);//converted image in variable 'data'
      }
      img.src = e.target.result;
    }
    filerdr.readAsDataURL(input.files[0]);
  }
}

I haven't tested this yet, but it should work.

我还没有测试过这个,但它应该可以工作。

Resize image with javascript canvas (smoothly)

使用 javascript 画布调整图像大小(平滑)