使用readAsDataURL方法预览图片

<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
<title>通过filereader接口读取文件</title>  
<script type="text/javascript">  
function readAsDataURL()  
{  
    if(typeof FileReader=='undifined')          //判断浏览器是否支持filereader  
    {  
        result.innerHTML="<p>抱歉,你的浏览器不支持 FileReader</p>";  
        return false;  
    }  
    var file=document.getElementById("imagefile").files[0];  
    if(!/image/w+/.test(file.type))           //判断获取的是否为图片文件  
    {  
        alert("请确保文件为图像文件");  
        return false;  
    }  
    var reader=new FileReader();  
    reader.readAsDataURL(file);  
    reader.onload=function(e)  
    {  
        var result=document.getElementById("result");  
        result.innerHTML='<img src="'+this.result+'" alt=""/>'  
    }  
      
}  
</script>  
</head>  
  
<body>  
<p>  
    <label>请选择一个文件:</label>  
    <input type="file" id="imagefile" />  
    <input type="button" value="读取图像" onClick="readAsDataURL();" />  
</p>  
<div name="result" id="result">  
    <!-- 这里用来显示图片结果-->  
</div>  
</body>  
</html> 

  使用FileReader接口的readAsDataURL方法实现图片的预览。

<template>
  <div class="vs-upload">
    <div>
      <div class="vs-upload__show" v-if="showimg">
        <img :src="img" width="100%" >
      </div>
      <div class="vs-upload__show" v-else>
        <div class="vs-upload__picture" :style="'backgroundImage:url('+headerImage+')'"></div>
      </div>
      <label for="upload" class="vs-upload__select">修改头像</label>
      <input type="file" id="upload" accept="image" @change="onUpload" style="margin-left: -999999px;">
    </div>
  </div>
</template>
<script>

export default {
  name: 'v-upload',
  props:{
    img:'',
    id:''
  },
  data() {
    return {
      showimg:false,
      headerImage: '',
      picValue: ''
    }
  },
  created: function() {
    if(this.headerImage != null){
      this.showimg=true
    }else{
      this.showimg=false
    }
  },
  mounted() {},
  methods: {
    onUpload(e) {
      this.showimg=false;
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.picValue = files[0];
      this.imgPreview(this.picValue);
    },
    imgPreview(file) {
      let self = this;
      let Orientation; 
      if (!file || !window.FileReader) return;

      if (/^image/.test(file.type)) {
        let reader = new FileReader(); 
        reader.readAsDataURL(file);
        reader.onloadend = function() {
          let result = this.result;
          let img = new Image();
          img.src = result;
          if (this.result.length <= (100 * 1024)) {
            self.headerImage = this.result;
            self.postImg();
          } else {
            img.onload = function() {
              let data = self.compress(img, Orientation);
              self.headerImage = data;
              self.postImg();
            }
          }
        }
      }
    },
    postImg() {
      this.$emit('upload', this.headerImage)
    },
    rotateImg(img, direction, canvas) {     
      const min_step = 0;
      const max_step = 3;
      if (img == null) return;    
      let height = img.height;
      let width = img.width;
      let step = 2;
      if (step == null) {
        step = min_step;
      }
      if (direction == 'right') {
        step++;  
        step > max_step && (step = min_step);
      } else {
        step--;
        step < min_step && (step = max_step);
      }  
      let degree = step * 90 * Math.PI / 180;
      let ctx = canvas.getContext('2d');
      switch (step) {
        case 0:
          canvas.width = width;
          canvas.height = height;
          ctx.drawImage(img, 0, 0);
          break;
        case 1:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, 0, -height);
          break;
        case 2:
          canvas.width = width;
          canvas.height = height;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, -height);
          break;
        case 3:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, 0);
          break;
      }
    },
    compress(img, Orientation) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext('2d');
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      let ratio;
      if ((ratio = width * height / 4000000) > 1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      let count;
      if ((count = width * height / 1000000) > 1) {
        count = ~~(Math.sqrt(count) + 1); 
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      if (Orientation != "" && Orientation != 1) {
        switch (Orientation) {
          case 6: 
            this.rotateImg(img, 'left', canvas);
            break;
          case 8: 
            this.rotateImg(img, 'right', canvas);
            break;
          case 3: 
            this.rotateImg(img, 'right', canvas); 
            this.rotateImg(img, 'right', canvas);
            break;
        }
      }
      let ndata = canvas.toDataURL('image/jpeg', 0.1);
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    },
  }
}

</script>
<style>
.vs-upload__show {
   100px;
  height: 100px;
  overflow: hidden;
  position: relative;
  border-radius: 50%;
  border: 1px solid #d5d5d5;
}

.vs-upload__picture {
   100%;
  height: 100%;
  overflow: hidden;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
}

</style>

  

原文地址:https://www.cnblogs.com/zhoubingyan/p/8779476.html