微信小程序 拍照和相機選擇詳解
前言:
小程序中獲取圖片可通過兩種方式得到,第一種是直接打開微信內部自己的樣式,第一格就是相機拍照,后面是圖片,第二種是彈框提示用戶是要拍照還是從相冊選擇,下面一一來看。
選擇相冊要用到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 bindtap="chooseimage">獲取圖片</button>
<image src="{{tempFilePaths }}" catchTap="chooseImageTap" mode="aspectFit" />
官方文檔:https://mp.weixin.qq.com/debug/wxadoc/dev/api/media-picture.html
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。