Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 896
Saranga Avatar asked Nov 25 '14 09:11

Saranga


1 Answers

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)

like image 127
nils Avatar answered Oct 05 '22 08:10

nils