1. 程式人生 > >微信小程式選擇圖片和預覽圖片

微信小程式選擇圖片和預覽圖片

作者>:燕瀟灑

視訊中,老師也是看著官方文件,為學生們講解,微信提供了系統的方法來選擇圖片.

wx.chooseImage({})

此方法是用來選擇圖片的方法,具體使用如下:

 data: {
    avatarUrl:null
  },

首先在資料中定義接收資料的變數,然後呼叫方法選擇圖片,將圖片顯示出來。

bindViewTap:function(){
    var that = this;
    wx.chooseImage({
    // 設定最多可以選擇的圖片張數,預設9,如果我們設定了多張,那麼接收時//就不在是單個變量了,
      count: 1
, sizeType: ['original', 'compressed'], // original 原圖,compressed 壓縮圖,預設二者都有 sourceType: ['album', 'camera'], // album 從相簿選圖,camera 使用相機,預設二者都有 success: function(res){ // 獲取成功,將獲取到的地址賦值給臨時變數 var tempFilePaths = res.tempFilePaths; that.setData({ //將臨時變數賦值給已經在data中定義好的變數
avatarUrl:tempFilePaths }) }, fail: function(res) { // fail }, complete: function(res) { // complete } }) }

此時我們定義的全域性變數,也就是data中的url,已經有值了,現在只需要在頁面中顯示即可。

//點選此按鈕呼叫選擇圖片的方法,成功後將圖片顯示在image標籤上
 <button bindtap="bindViewTap" type="submit"
>
繫結事件</button> <image src="
{{avatarUrl}}"></image>

如果是多選的話,在顯示的時候,就不應該直接顯示資料來源了,這樣會報錯的,因為返回的是陣列:

<image wx:for="{{avatarUrl}}"  wx:key="unique" src="{{item}}"></image>

圖片預覽:
下面說一下圖片預覽:
首先在data中定義好資料來源:

  data:{
    avatarUrl:null,
    pictures: [ 'https://p0.meituan.net/movie/ea4ac75173a8273f3956e514a4c78018253143.jpeg',
      'https://p0.meituan.net/movie/5d4fa35c6d1215b5689257307c461dd2541448.jpeg',
      'https://p0.meituan.net/movie/0c49f98a93881b65b58c349eed219dba290900.jpg',
      'https://p1.meituan.net/movie/45f98822bd15082ae3932b6108b17a01265779.jpg',
      'https://p1.meituan.net/movie/722de9a7b0c1f9c262162d87eccaec7c451290.jpg',
      'https://p0.meituan.net/movie/cb9be5bbedb78ce2ef8e83c93f83caca474393.jpg',
      'https://p1.meituan.net/movie/a852b992cdec15319c717ba9fa9b7a35406466.jpg',
      'https://p1.meituan.net/movie/dc1f94811793e9c653170cba7b05bf3e484939.jpg'
    ]
  },

然後建立方法previewImage,實現圖片預覽:

  previewImage: function(e){
    var that = this,
    //獲取當前圖片的下表
        index = e.currentTarget.dataset.index,
        //資料來源
        pictures = this.data.pictures;
    wx.previewImage({
    //當前顯示下表
      current: pictures[index],
      //資料來源
      urls: pictures
    })
  }

然後再頁面中邊遍歷資料,顯示:

<view>
 <image wx:for="{{pictures}}" wx:key="unique"src="{{item}}" data-index="{{index}}" bindtap="previewImage"></image>
</view>

先列表顯示全部圖片,繫結預覽方法,點選圖片進行左右預覽,