这篇文章主要介绍了微信小程序开发之相册选择和拍照详解及实例代码的相关资料,需要的朋友可以参考下
微信小程序 拍照和相机选择详解
前言:
小程序中获取图片可通过两种方式得到,第一种是直接打开微信内部自己的样式,第一格就是相机拍照,后面是图片,第二种是弹框提示用户是要拍照还是从相册选择,下面一一来看。
选择相册要用到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" />
官方文档:https://mp.weixin.qq.com/debug/wxadoc/dev/api/media-picture.html
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
微信小程序多张图片上传功能的实现
微信小程序实现登录页云层漂浮的动画效果
关于微信小程序中上传头像的代码
以上就是微信小程序中相册选择和拍照的介绍的详细内容。