官網里面的代碼,使用chooseImage
即可,count
表示最多可以選擇的圖片張數, sizeType
表示所選的圖片的尺寸sourceType
表示選擇圖片的來源,詳情可以仔細閱讀一下文檔。
wx.chooseImage({
count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success(res) { // tempFilePath可以作為img標簽的src屬性顯示圖片 const tempFilePaths = res.tempFilePaths } })
有很多功能設計的時候是這樣的,點擊按鈕之后會從手機的底部彈出來一個詢問按鈕,詢問是從手機里選擇一張照片,還是調用攝像功能拍攝照片,這個時候其實只要多調用一下這個函數showActionSheet就可以了。
效果如下:點擊按鈕,選擇圖片進行替換,或者拍到一張照片,進行更換。
代碼:
wxml:
<view class="container"> <view> <button class="btn" bindtap="chooseimage">點擊更換圖片</button> </view> <view> <image src="{{img}}" catchTap="chooseImageTap" mode="aspectFit" class="img" /> </view> </view>
wxss:
.btn {
margin: 140rpx;
}
.img {
width: 100%; height: 480rpx; }
js
Page({
data: {
img: '../../images/1.jpg' }, onLoad: function() {}, chooseWxImage: function(type) { var that = this; wx.chooseImage({ sizeType: ['original', 'compressed'], sourceType: [type], success: function(res) { console.log(res); that.setData({ // tempFilePath可以作為img標簽的src屬性顯示圖片 img: res.tempFilePaths[0], }) } }) }, chooseimage: function() { var that = this; wx.showActionSheet({ itemList: ['從相冊中選擇', '拍照'], itemColor: "#a3a2a2", success: function(res) { if (!res.cancel) { if (res.tapIndex == 0) { that.chooseWxImage('album') } else if (res.tapIndex == 1) { that.chooseWxImage('camera') } } } }) }, })