H5移動端調用相機或相冊

一: 前提

????在做H5時,有時要實現拍照功能,這就要調取手機端的相機,當時,在網上搜了很多能實現的方式,最后還是用html5自帶的 input標簽,實現移動端調用手機攝像頭。好了,話不多說,下面就是我實現的代碼:

二:實現

(一):調用手機相機或相冊

      <!--圖片二-->
        <label for="xFile2" style="padding-top:15px;" class=" cameraImg2" @click="removeImg2();">
          <span v-if="imgList2.length == ''" class="glyphicon-camera" >
            <p style="line-height:5px;">
             <label>圖片二</label>
            <!--調取相機-->
             <input type="file" id="xFile2" capture="camera" multiple="multiple" accept="image/*" class="imgInp1" @change='onUpload2($event)'  style="position:absolute;clip:rect(0 0 0 0); width: 100%; height: 105px; top:0px;" v-if="judgeFan">
           </p>
         </span>
        </label>

???? 其中input標簽type="file"的參數capture表示,可以捕獲到系統默認的設備,比如:camera照相機;camcorder攝像機;microphone錄音,accept表示,直接打開系統文件目錄,multiple屬性,表示可以支持多選。

(二): 獲取圖片同時壓縮,然后傳給后臺


    // 解決ios照片旋轉問題
    //獲取照片的拍攝方向
    getOrientation(file, callback){
      var reader = new FileReader();
      reader.onload = function(e) {
        var view = new DataView(e.target.result);
        if (view.getUint16(0, false) != 0xFFD8){
          return callback(-2);
        }
        var length = view.byteLength, offset = 2;
        while (offset < length) {
          var marker = view.getUint16(offset, false);
          offset += 2;
          if (marker == 0xFFE1) {
            if (view.getUint32(offset += 2, false) != 0x45786966){
              return callback(-1);
            }
            var little = view.getUint16(offset += 6, false) == 0x4949;
            offset += view.getUint32(offset + 4, little);
            var tags = view.getUint16(offset, little);
            offset += 2;
            for (var i = 0; i < tags; i++){
              if (view.getUint16(offset + (i * 12), little) == 0x0112)
                return callback(view.getUint16(offset + (i * 12) + 8, little));
            }
          }else if ((marker & 0xFF00) != 0xFF00){
            break;
          }else {
            offset += view.getUint16(offset, false);
          }
        }
        return callback(-1);
      };
      reader.readAsArrayBuffer(file);
    },

/*
獲取圖片的事件
*/
onUpload(input) {
      var _this = this;
      if (_this.judgeZheng) {
        _this.judgeZheng = false;
        _this.hideImg2=true;
      /*
       imglist 是定義的一個存放圖片的數組,來判斷只能上傳一張圖片
     */
        if (this.imgList.length >= 1) {
          $.alert("只能上傳一張照片!");
          return;
        }
        if (input.target.files && input.target.files[0]) {
          if (window.FileReader) {
            var name = input.target.value.substring(
              input.target.value.lastIndexOf(".") + 1,
              input.target.value.lastIndexOf(".").length
              );
            var timeStamp = input.timeStamp;
            /*
           創建一個FileReader對象,用來獲取文件
           */
            var reader = new FileReader();
            reader.onload = function(e) {
              var objs = {
                url: e.target.result,
                name: name,
                timeStamp: timeStamp
              };
              ysImg(objs, function(objs) {
                _this.imgListzheng = objs.url;
                _this.img_file = input;
                _this.thumbnailUrl = objs.url;
               _this.img_data = objs.url;
              _this.img_name ='11.jpg';
              _this.timeStamp = objs.timeStamp;
            });
              function ysImg(objs, callback) {
              //設置壓縮圖片的最大高度
              var imgarr = [];
              var MAX_HEIGHT = 1000;
              //獲取拍攝方向
              _this.getOrientation(input.target.files[0], function(orientation) {
                _this.orientation = orientation;
              });
              // 創建一個 Image 對象
              var image = new Image();
              image.src = objs.url;
              // 綁定 load 事件處理器,加載完成后執行
              image.onload = function() {
                // 獲取 canvas DOM 對象
                var canvas = document.createElement("canvas");
                // 如果高度超標
                if (image.height > MAX_HEIGHT && image.height >= image.width) {
                  // 寬度等比例縮放 *=
                  image.width *= MAX_HEIGHT / image.height;
                  image.height = MAX_HEIGHT;
                }
                //考錄到用戶上傳的有可能是橫屏圖片同樣過濾下寬度的圖片。
                if (image.width > MAX_HEIGHT && image.width > image.height) {
                  // 寬度等比例縮放 *=
                  image.height *= MAX_HEIGHT / image.width;
                  image.width = MAX_HEIGHT;
                }
                // 獲取 canvas的 2d 畫布對象,
                var ctx = canvas.getContext("2d");
                // canvas清屏,并設置為上面寬高
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                // 重置canvas寬高
                canvas.width = image.width ;
                canvas.height = image.height ;
                //判斷圖片拍攝方向是否旋轉了90度
                if(_this.orientation == 6){
                  var x = canvas.width / 2;                //畫布寬度的一半
                  var y = canvas.height / 2;               //畫布高度的一半
                  ctx.clearRect(0,0, canvas.width, canvas.height);           //先清掉畫布上的內容
                  ctx.translate(x,y);                      //將繪圖原點移到畫布中點
                  ctx.rotate( (Math.PI / 180) * 90 );      //旋轉角度
                  ctx.translate(-x,-y);                    //將畫布原點移動
                  ctx.drawImage(image, 0, 0, image.width, image.height);       //繪制圖片
                }else{
                  // 將圖像繪制到canvas上
                  ctx.drawImage(image, 0, 0, image.width, image.height);
                  // !!! 注意,image 沒有加入到 dom之中
                  //        document.getElementById('img').src = canvas.toDataURL("image/png");
                }
                _this.blob = canvas.toDataURL("image/jpeg",0.5);
                if (objs.url.length <_this.blob.length) {
                  objs.url = objs.url;
                } else {
                  objs.url =_this.blob;
                }
                var arrName=_this.blob.split(",");
                var strName1=arrName[1];
                 /* 將獲取的圖片資源通過接口上傳到后臺
                */
                _this.API.post('/gateway/gateway',{fileContent:strName1,fileName:'11.jpg',fileType:"A01"})
                .then(function(res){
                 if(res.code=="000000"){
                  if(res.data.idCardNumber) {
                   _this.noName=res.data.name;
                   _this.noIdCardNumber=res.data.idCardNumber;
                   if(_this.blob3) {
                     _this.name=_this.noName;
                     _this.idCardNumber =  _this.noIdCardNumber
                   }
                 } 
                 _this.imgList.push(_this.imgListzheng);
               }else{
                _this.imgList=[];
                _this.judgeZheng = true;   
              }
            })
                //將轉換結果放在要上傳的圖片數組里
                callback(objs);
              };
            }
          };
          reader.onabort = function() {
            alert("上傳中斷");
          };
          reader.onerror = function() {
            alert("上傳出錯");
          };
          reader.readAsDataURL(input.target.files[0]);
        } else {
          alert("Not supported by your browser!");
        }
      }
    } else {
    }
  },

親測有用喲。如果對你有幫助,用你的小手幫忙點個贊喲。 ?( ′???` )比心

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網絡請求組件 FMDB本地數據庫組件 SD...
    陽明AGI閱讀 16,018評論 3 119
  • 轉載請注明出處(http://www.lxweimin.com/p/5f538820e370),您的打賞是小編繼續...
    福later閱讀 28,188評論 8 73
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,991評論 19 139
  • Hi~大家來看看發文表吧ヾ(≧?≦*)ヾ 正文: 二兩個星期一次(查理九世冒險旅程) 番外: 一個月一兩篇(水晶狐...
    紙杯蛋糕閱讀 311評論 8 3
  • 一個笨人的經歷,我是如何從股市里面搞些零錢的 本人是一個老股民,還是一個比較笨的老股民,基本上每次買股票,買10回...
    雨過天不晴_0fc2閱讀 249評論 0 0