4***@qq.com
4***@qq.com
  • 发布:2019-04-11 18:35
  • 更新:2020-11-12 13:43
  • 阅读:2851

拍照,相册,读取图片转成File

分类:HTML5+
/* global plus:true */  
/* eslint prefer-promise-reject-errors: "error" */  

/*  
拍照 = capture = readFile + saveInGallery  
*  
相册 = readFile  
*  
readFile = compress + checkSize + turnToFile  
         = 压缩》检查大小(this.maxSize)》转成File文件  
*/  

class UploadImg {  
  constructor () {  
    this.maxSize = 5 // 最大5M  
    this.quality = 20 // 1-100,越高图越大  
  }  
  capture () {  
    plus.nativeUI.showWaiting();  
    const _this = this  
    var cmr = plus.camera.getCamera();  
    // res分辨率  
    var res = cmr.supportedImageResolutions[0];  
    // fmt文件格式  
    var fmt = cmr.supportedImageFormats[0];  
    return new Promise((resolve, reject) => {  
      cmr.captureImage(function (p) {  
        Promise.all([_this.saveInGallery(p), resolve(_this.readFile(p))])  
          .then(() => plus.nativeUI.closeWaiting())  
          .catch(() => plus.nativeUI.closeWaiting())  
      },  
      function (error) {  
        reject(error)  
        plus.nativeUI.closeWaiting()  
      }, {  
        resolution: res,  
        format: fmt  
      })  
    })  
  }  
  gallery () {  
    plus.nativeUI.showWaiting();  
    const _this = this  
    return new Promise((resolve, reject) => {  
      plus.gallery.pick(  
        function (p) {  
          Promise.all([resolve(_this.readFile(p))])  
            .then(() => plus.nativeUI.closeWaiting())  
            .catch(() => plus.nativeUI.closeWaiting())  
        },  
        function (cancel) {  
          reject(cancel)  
          plus.nativeUI.closeWaiting()  
        }, {  
          filter: 'image'  
        }  
      )  
    })  
  }  
  saveInGallery (p) {  
    plus.gallery.save(p, function () {  
      console.log('保存进相册-成功')  
    },  
    function () {  
      console.log('保存进相册-失败')  
    })  
  }  
  compress (p) {  
    const _this = this  
    return new Promise((resolve, reject) => {  
      plus.zip.compressImage({  
        src: p,  
        dst: '_doc/compress.jpg',  
        overwrite: true,  
        quality: _this.quality  
      },  
      function (file) {  
        resolve(file.target)  
      },  
      function (error) {  
        console.log('压缩失败');  
        reject(error)  
      });  
    })  
  }  
  checkSize (size) {  
    const _this = this  
    return new Promise((resolve, reject) => {  
      const num = 1024;  
      const fileSize = (size / Math.pow(num, 2)).toFixed(2);  
      if (fileSize > _this.maxSize) {  
        plus.nativeUI.alert(`图片不得超过${_this.maxSize}M`);  
        reject(new Error('overSize'));  
      } else {  
        resolve()  
      }  
    })  
  }  
  readFile (p) {  
    const _this = this  
    return new Promise((resolve, reject) => {  
      this.compress(p).then((p) => {  
        plus.io.resolveLocalFileSystemURL(p, function (fs) {  
          fs.file(function (file) {  
            _this.checkSize(file.size)  
              .then(() => {  
                resolve(_this.turnToFile(fs, file))  
              })  
              .catch(error => {  
                console.log(error)  
              })  
          });  
        });  
      })  
    });  
  }  
  turnToFile (fs, oldFile) {  
    return new Promise((resolve, reject) => {  
      var reader = new plus.io.FileReader();  
      reader.readAsDataURL(oldFile)  
      reader.onloadend = function (e) {  
        // e.target.result  
        let data = e.target.result  
        // object专成file  
        let file = (function (path, name) {  
          let arr = path.split(',')  
          let mime = arr[0].match(/:(.*?);/)[1]  
          let bstr = atob(arr[1])  
          let n = bstr.length  
          let u8arr = new Uint8Array(n)  
          while (n--) {  
            u8arr[n] = bstr.charCodeAt(n);  
          }  
          return new File([u8arr], name, {  
            type: mime  
          });  
        })(e.target.result, fs.name);  
        resolve({  
          data: data,  
          file: file  
        })  
      };  
    })  
  }  
}  
export const uploadImg = new UploadImg()
0 关注 分享

要回复文章请先登录注册

8***@qq.com

8***@qq.com

这么棒,顶一下
2020-11-12 13:43
4***@qq.com

4***@qq.com (作者)

import { uploadImg } from "地址"
// 拍照
takePhoto () {
uploadImg.capture().then(res => {});
},
// 相册
openAlbum () {
uploadImg.gallery().then(res => {});
}

res的格式是
{
data: base64的图片,
file: file类型的object
}
2019-04-23 14:15