zoukankan      html  css  js  c++  java
  • HTML5图片上传本地预览

    在开发 H5 应用的时候碰到一个问题,
    应用只需要一张小的缩略图,
    而用户用手机上传的确是一张大图,
    手机摄像机拍的图片好几 M,这可要浪费很多流量。

    我们可以通过以下方式来解决。

    获取图片

    通过 File API 获取图片。

    var input = document.createElement('input');
    input.type = 'file';
    input.addEventListener('change', function() {
      var file = this.files[0];
    });
    input.click();

    预览图片

    使用 createObjectURL() 或者 FileReader 预览图片

    var img = document.createElement('img');
    img.src = window.URL.createObjectURL(file);
    var img = document.createElement("img");
    var reader = new FileReader();
    reader.onload = function(e) {
      img.src = e.target.result;
    }
    reader.readAsDataURL(file);

    使用 canvas 做缩略图

    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var MAX_WIDTH = 800;
    var MAX_HEIGHT = 600;
    var width = img.width;
    var height = img.height;
    
    if (width > height) {
      if (width > MAX_WIDTH) {
        height *= MAX_WIDTH / width;
        width = MAX_WIDTH;
      }
    } else {
      if (height > MAX_HEIGHT) {
        width *= MAX_HEIGHT / height;
        height = MAX_HEIGHT;
      }
    }
    canvas.width = width;
    canvas.height = height;
    ctx.drawImage(img, 0, 0, width, height);

    上传缩略图

    canvas.toBlob(function(blob) {
      var form = new FormData();
      form.append('file', blob);
      fetch('/api/upload', {method: 'POST', body: form});
    });

    结语

    toBlob的兼容性问题我们引用一下这个库就可以了 https://github.com/blueimp/JavaScript-Canvas-to-Blob 

  • 相关阅读:
    leetcode69
    leetcode204
    leetcode414
    leetcode532
    leetcode28
    leetcode155
    leetcode303
    leetcode190
    2018-7-21-win10-uwp-调用-Microsoft.Windows.Photos_8wekyb3d8bbwe-应用
    2018-7-21-win10-uwp-调用-Microsoft.Windows.Photos_8wekyb3d8bbwe-应用
  • 原文地址:https://www.cnblogs.com/zhouyangla/p/7975429.html
Copyright © 2011-2022 走看看