1. 程式人生 > >微信小程式之相簿選擇,拍照

微信小程式之相簿選擇,拍照

小程式中獲取圖片可通過兩種方式得到,第一種是直接開啟微信內部自己的樣式,第一格就是相機拍照,後面是圖片,第二種是彈框提示使用者是要拍照還是從相簿選擇,下面一一來看。
選擇相簿要用到wx.chooseImage(OBJECT)函式,具體引數如下:
這裡寫圖片描述

直接來看開啟相機相簿的程式碼:

Page({
  data: {
    tempFilePaths: ''
  },
  onLoad: function () {
  },
  chooseimage: function () {
    var that = this;
    wx.chooseImage({
      count: 1
, // 預設9 sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有 sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有 success: function (res) { // 返回選定照片的本地檔案路徑列表,tempFilePath可以作為img標籤的src屬性顯示圖片 that.setData({ tempFilePaths: res.tempFilePaths }) } }) }, })

方法一效果圖如下:
這裡寫圖片描述

個人認為第二種使用者體驗要好一點,效果如下:
這裡寫圖片描述

點選獲取彈框提示,程式碼如下:

Page({
  data: {
    tempFilePaths: ''
  },
  onLoad: function () {
  },
  chooseimage: function () {
    var that = this;
    wx.showActionSheet({
      itemList: ['從相簿中選擇', '拍照'],
      itemColor: "#CED63A",
      success: function (res) {
        if
(!res.cancel) { if (res.tapIndex == 0) { that.chooseWxImage('album') } else if (res.tapIndex == 1) { that.chooseWxImage('camera') } } } }) }, chooseWxImage: function (type) { var that = this; wx.chooseImage({ sizeType: ['original', 'compressed'], sourceType: [type], success: function (res) { console.log(res); that.setData({ tempFilePaths: res.tempFilePaths[0], }) } }) } })

檔案的臨時路徑,在小程式本次啟動期間可以正常使用,如需持久儲存,需在主動呼叫 wx.saveFile,在小程式下次啟動時才能訪問得到。

佈局檔案:

<button style="margin:30rpx;" bindtap="chooseimage">獲取圖片</button>
<image src="{{tempFilePaths }}" catchTap="chooseImageTap" mode="aspectFit" style="width: 100%; height: 450rpx" />