1. 程式人生 > >H5呼叫相機和相簿更換頭像

H5呼叫相機和相簿更換頭像

需求:H5呼叫手機的相機和相簿從而實現更換頭像的功能

這個功能是很常用的一個功能,因此做一個記錄。

1.在頭像img下加一個檔案輸入框

<input type="file" id="file" accept="image/*" capture='camera' multiple>

並隱藏之

1 <center>
2    <img src="images/[email protected]" class="avatar">
3    <input type="file" id="file" accept="image/*" capture='camera' multiple>
4 </center>
1 #file {
2    display: none;
3 }

 

2.點選頭像觸發檔案輸入框點選事件

$(".avatar").click(function(){
    $("#file").trigger("click")
})

 

3.通過js拿到上傳的檔案內容,轉成base64編碼並顯示圖片在頁面上

 1 //ios去掉capture屬性
 2 var file = document.querySelector('input');
 3 if (getIos()) {
 4   file.removeAttribute("capture");
 5 }
 6 function getIos() {
 7   var ua = navigator.userAgent.toLowerCase();
 8   if (ua.match(/iPhone\sOS/i) == "iphone os") {
 9      return true;
10   } else {
11      return false;
12   }
13 }
 1 //轉成base64
 2 $('input[type=file]').on('change', function () {
 3     var reader = new FileReader();
 4     reader.onload = function (e) {
 5         console.log(reader.result);  //或者 e.target.result都是一樣的,都是base64碼
 6         $(".avatar").attr("src", reader.result);
 7      }
 8     reader.readAsDataURL(this.files[0])
 9     //filses就是input[type=file]檔案列表,files[0]就是第一個檔案,這裡就是將選擇的第一    個圖片檔案轉化為base64的碼
10 }) 

 

4.實現效果頁面展示

更換頭像前的效果:

 

 更換頭像後的效果:

&n