初学有不当之处,请多多指点,

 

<body>
  <div class=”cc”>
    <input type=”file” id=”file” onchange=”imgChange()” accept=”image/*”>
  </div>
  <img src=”” id=”showImage” alt=””>
<!– <canvas id=”canvas” style=”display: none;”></canvas> –>

<script>
  function imgChange(){
    var file = document.getElementById(‘file’).files[0] //获取选择上传的图片文件

    var reader = new FileReader() //声明一个新构的FileReader
    reader.readAsDataURL(file) //把图片变成base64
    reader.onload = function(){

      var showImage = document.getElementById(‘showImage’)

      if (file.size > 100 * 100) { //判断图片的大小
        showImage.src = reader.result //赋值给img选择的图片
        showImage.onload = function(){ //当img全部加载完后
          var canvas = document.createElement(‘canvas’)//创建canvas对象
          canvas.width = this.width //设置画布的宽高和showImage图片的大小一致
          canvas.height = this.height
          var cgt = canvas.getContext(‘2d’) //设置二维画布环境
          cgt.drawImage(this,0,0,canvas.width,canvas.height)

          showImage.src = canvas.toDataURL(“image/jpeg”, 0.4) //改变画布的格式和图片质量
        }
    }
    else{
      showImage.src = reader.result
    }
  }

}
</script>
</body>

 

版权声明:本文为mei1234原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/mei1234/p/8465633.html