选择并预览图片

html:

<input id="file" @change="changeImg($event)" type="file" class="file" accept="image/png,image/jpeg,image/gif">

js:

changeImg(event){

    var files = $(event.currentTarget)[0].files[0]; //传递后台

    var self = this;

    function getObjectURL(file) {

        var url = null ;

        if (window.createObjectURL!=undefined) { // basic

              url = window.createObjectURL(file) ;

       } else if (window.URL!=undefined) { // mozilla(firefox)

              url = window.URL.createObjectURL(file) ;

       } else if (window.webkitURL!=undefined) { // webkit or chrome

             url = window.webkitURL.createObjectURL(file) ;

      }

      return url ;

    }

   function convertImgToBase64(url, callback, outputFormat){

      var canvas = document.createElement('CANVAS');

      var ctx = canvas.getContext('2d');

      var img = new Image;

      img.crossOrigin = 'Anonymous';

      img.onload = function(){

      var width = img.width;

      var height = img.height;

      var rate = (width<height ? width/height : height/width)/4;

      canvas.width = width*rate;

      canvas.height = height*rate;

      ctx.drawImage(img,0,0,width,height,0,0,width*rate,height*rate);

      var dataURL = canvas.toDataURL(outputFormat || 'image/png');

      callback.call(this, dataURL);

      canvas = null;

  };

  img.src = url;

  }

  // var files=$(event.currentTarget)[0]

  var imageUrl=getObjectURL($(event.currentTarget)[0].files[0])

  var input=$(event.currentTarget)

  convertImgToBase64(imageUrl, function(base64Img){

  input.next().attr('src',base64Img)

  });

},

猜你喜欢

转载自blog.csdn.net/Lei_zhen96/article/details/81985820
今日推荐