Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

html - resize image using javascript

I'm using javascript function to input image.

This is my 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:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...