resize image using javascript

后端 未结 1 1093

I\'m using javascript function to input image.

This is my HTML:



        
1条回答
  •  半阙折子戏
    2020-12-19 04:23

    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)

    0 讨论(0)
提交回复
热议问题