base64显示图片








请选取一个图像文件:



 

兼容ie的写法 (还没有整理)

 function PreviewImg(el,previewEl,opts){
      this.$el=$(el);
      this.$previewEl=$(previewEl);

      //上传图片触发change事件,改变this指向
      var that=this;
      this.$el.change(function(){
        $.proxy(that.preview(this),that)    
      })


      this.opts=$.extend({},PreviewImg.DEFAULTS,opts)

    }

    //预览图片
    PreviewImg.prototype.preview=function(file){
      var objthis=this;
      var maxWidth  =objthis.opts.maxWidth; 
      var maxHeight = objthis.opts.maxHeight;
      var $previewEl = objthis.$previewEl;
      $previewEl.html('')
      var img = $('#preImg').get(0);
      if (file.files && file.files[0])
      {
        img.onload = function(){
         var rect = objthis._cutImg(maxWidth, maxHeight, img.offsetWidth, img.offsetHeight);
         img.width  =  rect.width;
         img.height =  rect.height;
         img.style.marginLeft = rect.left+'px';
         img.style.marginTop = rect.top+'px';
       }
       var reader = new FileReader();
       reader.onload = function(evt){img.src = evt.target.result;}
       reader.readAsDataURL(file.files[0]);
     }
     else 
     {
      var sFilter='filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
        file.select();
        var src = document.selection.createRange().text;       
        img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
        var rect = objthis._cutImg(maxWidth, maxHeight, img.offsetWidth, img.offsetHeight);
        $previewEl.html("
"); } } //裁剪图片,等比缩放尺寸 PreviewImg.prototype._cutImg=function(maxWidth, maxHeight, width, height){ var param = {top:0, left:0, width:width, height:height}; if( width>maxWidth || height>maxHeight ) { rateWidth = width / maxWidth; rateHeight = height / maxHeight; if( rateWidth > rateHeight ) { param.width = maxWidth; param.height = Math.round(height / rateWidth); }else { param.width = Math.round(width / rateHeight); param.height = maxHeight; } } param.left = Math.round((maxWidth - param.width) / 2); param.top = Math.round((maxHeight - param.height) / 2); return param; } //默认参数,预览图片的宽高限制 PreviewImg.DEFAULTS={ maxHeight:190, maxWidth:260 }

你可能感兴趣的:(base64显示图片)