微信小程序开发之相册选择和拍照详解及实例代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

微信小程序开发之相册选择和拍照详解及实例代码

  2020-05-15 我要评论

微信小程序 拍照和相机选择详解

前言:

小程序中获取图片可通过两种方式得到,第一种是直接打开微信内部自己的样式,第一格就是相机拍照,后面是图片,第二种是弹框提示用户是要拍照还是从相册选择,下面一一来看。

选择相册要用到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.comhttps://img.qb5200.com/download-x/debug/wxadochttps://img.qb5200.com/download-x/dev/api/media-picture.html

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们