微信小程序拍照和相册选取图片

本文介绍如何在微信小程序中进行布局设置、应用样式,并实现从相机和相册选择图片的功能,最终展示图片并保存。内容包括布局设计、图片路径获取及图片显示的相关代码操作。

布局:

<!--pages/camera/camera.wxml-->
<view 
class="tui-menu-list" 
id="view1" 
style="display:flex;flex-direction:space-between">
	<button 
		id="b1" 
		size="mini"
		type="primary" 
		bindtap="chooseimage">
		获取图片
	</button>
	<button 
		id="b2" 
		size="mini"
		type="primary"
		bindtap="savePhone">
		保存
	</button>
</view>

<image
	 src="{{tempFilePaths}}" 
	 catchtap="chooseImageTap"
	 mode="aspectFit" 
	 style="width:100%;height:400px;background-color:#ffffff;">
</image>

样式:

/* pages/camera/camera.wxss */

.view1 {
  height: 25px
}

.tui-menu-list {
  display: flex;
  flex-direction: row;
  margin: 20rpx;
  padding: 20rpx;
}

 

获取图片路径,显示图片和保存

// pages/camera/camera.js
Page({

  data: {
    tempFilePaths: 'http://pic2.cxtuku.com/00/01/08/b207004f7104.jpg'
  },
  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],
      count: 1,
      success: function (res) {
        console.log(res)
        that.setData({
          tempFilePaths: res.tempFilePaths[0],
        })
      }
    })
  },
  savePhone: function () {
    wx.getImageInfo({
      src: this.data.tempFilePaths,
      success: function (res) {
        var path = res.path
        wx.saveImageToPhotosAlbum({
          filePath: path,
          success: function () {
            wx.showToast({
              title: '保存成功',
            })
          },
          fail: function (res) {
            wx.showToast({
              title: '保存失败',
              icon: 'none'
            })
          }
        })
      }
    })
  }
})

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值