微信小程序開發(fā)之相冊選擇和拍照詳解及實例代碼
微信小程序 拍照和相機(jī)選擇詳解
前言:
小程序中獲取圖片可通過兩種方式得到,第一種是直接打開微信內(nèi)部自己的樣式,第一格就是相機(jī)拍照,后面是圖片,第二種是彈框提示用戶是要拍照還是從相冊選擇,下面一一來看。
選擇相冊要用到wx.chooseImage(OBJECT)函數(shù),具體參數(shù)如下:

直接來看打開相機(jī)相冊的代碼:
Page({
data: {
tempFilePaths: ''
},
onLoad: function () {
},
chooseimage: function () {
var that = this;
wx.chooseImage({
count: 1, // 默認(rèn)9
sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機(jī),默認(rèn)二者都有
success: function (res) {
// 返回選定照片的本地文件路徑列表,tempFilePath可以作為img標(biāo)簽的src屬性顯示圖片
that.setData({
tempFilePaths: res.tempFilePaths
})
}
})
},
})
方法一效果圖如下:

個人認(rèn)為第二種用戶體驗要好一點,效果如下:

點擊獲取彈框提示,代碼如下:
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],
})
}
})
}
})
文件的臨時路徑,在小程序本次啟動期間可以正常使用,如需持久保存,需在主動調(diào)用 wx.saveFile,在小程序下次啟動時才能訪問得到。
布局文件:
<button style="margin:30rpx;" bindtap="chooseimage">獲取圖片</button>
<image src="{{tempFilePaths }}" catchTap="chooseImageTap" mode="aspectFit" style="width: 100%; height: 450rpx" />
官方文檔:https://mp.weixin.qq.com/debug/wxadoc/dev/api/media-picture.html
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
微信小程序 實戰(zhàn)實例開發(fā)流程詳細(xì)介紹
這篇文章主要介紹了微信小程序 實戰(zhàn)實例開發(fā)流程詳細(xì)介紹的相關(guān)資料,這里主要介紹微信小程序的開發(fā)流程和簡單實例,需要的朋友可以參考下2017-01-01
JS前端使用canvas實現(xiàn)擴(kuò)展物體類和事件派發(fā)
這篇文章主要為大家介紹了JS前端使用canvas實現(xiàn)擴(kuò)展物體類和事件派發(fā)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08

