codecamp

百度智能小程序 打开本地相册

swan.chooseAlbum

基础库 3.30.3 开始支持,低版本需做兼容处理

解释:打开本地相册,相册内可以同时包含图片和视频。

方法参数

Object object

object 参数说明

属性名类型必填默认值说明

count

Number

9

最多可以选择的图片/视频数量。

mode

String

single

打开相册后可选择资源类型设置, 可选择模式为: single/both; single: 打开相册后只能选择图片或视频; both: 打开相册后,可以同时选择图片和视频。

compressed

Boolean

true

是否压缩所选的视频源文件,需要压缩。

success

Function

成功则返回图片或视频的本地文件路径列表 tempFilePaths。

fail

Function

接口调用失败的回调函数

complete

Function

接口调用结束的回调函数(调用成功、失败都会执行)

success 返回参数说明

参数类型说明

tempFilePaths

Array.<string>

选择资源(图片或视频)的本地文件路径列表 。

tempFiles

Array.<object>

选择资源(图片或视频)本地文件列表,每一项是一个 File 对象。

tempFiles 对象结构如下

字段类型说明

path

String

本地文件路径

size

Number

本地文件大小(单位:B)

type

文件类型

有效值:video、image (注:基础库 3.190.3 之前在选择资源为图片时 type 值返回 image 或 photo, 3.190.3 之后返回 image,低版本需做兼容处理)

duration

Number

选定视频的时间长度 (单位:s); 开发者工具暂不支持

示例 

在开发者工具中打开


图片示例

代码示例

<view class="wrap">
    <view class="card-area">
        <video s-if="hasVideo" style="width: 100%;" id="myVideo" src="{{videoSrc}}" autoplay="true" bindended="videoEnd"></video>
        <view s-else>        
            <view s-if="{{imageList.length > 0}}" class="image-container" style="height: {{imageList.length > 6 ? '3.54' : '2.55'}}rem;">
                <image s-for="img in imageList" bindtap="{{img.type == 'video' ? 'upVideo' : 'previewImage'}}"  data-src="{{img.videoSrc}}" class="image-items" style="height: {{imageList.length > 6 ? '32' : '49'}}%;" src="{{img.path}}" mode="scaleToFill"></image>
            </view>
            <view s-else class="display-area">
                图片/视频显示区
            </view>
        </view>
        <view class="middle-area border-top border-bottom">
            <view class="list-area border-bottom" hover-class="option-active">
                <text class="list-item-key-4">可选媒体</text>
                <picker class="list-item-value" mode="selector" value="{{sourceIndex}}" range="{{sourceArray}}" bind:change="sourceChange">
                    <view hover-class="hover">{{sourceArray[sourceIndex]}}</view>
                </picker>
            </view>
            <view class="list-area border-bottom" hover-class="option-active">
                <text class="list-item-key-4">是否压缩</text>
                <picker class="list-item-value" mode="selector" value="{{sizeIndex}}" range="{{sizeArray}}" bind:change="sizeChange">
                    <view hover-class="hover">{{sizeArray[sizeIndex]}}</view>
                </picker>
            </view>
            <view class="list-area border-bottom" hover-class="option-active">
                <text class="list-item-key-4">数量限制</text>
                <picker class="list-item-value" mode="selector" value="{{countIndex}}" range="{{countArray}}" bind:change="countChange">
                    <view hover-class="hover">{{countArray[countIndex]}}</view>
                </picker>
            </view>
        </view>
        <view class="button-group">
            <button type="primary" bindtap="selectImage">添加图片/视频</button>
            <button type="default" bindtap="clearImage">清空</button>
        </view>
    </view>
</view>
Page({
    data: {
        sourceIndex: 1,
        sourceArray: ['图片或视频', '图片及视频'],
        sizeIndex: 1,
        sizeArray: ['压缩', '不压缩'],
        countIndex: 0,
        countArray: [],
        imageList: [],
        videoSrc: '',
        hasVideo: false
    },
    onLoad(e) {
        const array = [];
        for (let i = 0; i < 9; i++) {
            array.push(i + 1);
        }
        this.setData({
            countIndex: array.length - 1,
            countArray: array
        });
    },
    sourceChange(e) {
        this.setData('sourceIndex', e.detail.value);
    },
    sizeChange(e) {
        this.setData('sizeIndex', e.detail.value);
    },
    countChange(e) {
        this.setData('countIndex', e.detail.value);
    },
    selectImage() {
        const sourceIndex = this.data.sourceIndex;
        const count = this.data.countIndex + 1;
        if (sourceIndex === 1) {
            const sourceType = 'both';
            this.chooseImage(sourceType, count);
        }
        else {
            const sourceType = 'single';
            this.chooseImage(sourceType, count);
        }
    },
    chooseImage(sourceType, count) {
        const sizeIndex = this.data.sizeIndex;
        let sizeType = [true, false];
        if (sizeIndex === 0) {
            sizeType = true;
        }
        else if (sizeIndex === 1) {
            sizeType = false;
        }

        swan.chooseAlbum({
            count: count,
            mode: sourceType,
            compressed: sizeType,
            success: res => {
                console.log('chooseAlbum success', res);
                let img = '';
                for (let i = 0; i < res.tempFiles.length; i++) {
                    if (res.tempFiles[i].type === 'video') {
                        res.tempFiles[i].videoSrc = res.tempFiles[i].path;
                        res.tempFiles[i].path = 'https://b.bdstatic.com/miniapp/image/default.png';
                    }

                    this.setData('imageList', res.tempFiles);
                    img = this.data.imageList;
                }
            },
            fail: err => {
                console.log('错误码:' + err.errCode);
                console.log('错误信息:' + err.errMsg);
            }
        });
    },
    videoEnd() {
        this.setData({
            hasVideo: false
        });
    },
    upVideo(e) {
        let src = e.currentTarget.dataset.src;
        this.setData({
            hasVideo: true,
            videoSrc: src
        });
    },
    clearImage() {
        const imageList = this.data.imageList;
        if (imageList.length > 0) {
            this.setData({
                imageList: [],
                hasVideo: false
            });
            swan.showToast({
                title: '清空成功',
                icon: 'none'
            });
        }
        else {
            swan.showToast({title: '无可清空图片', icon: 'none'});
        }
    },
    previewImage(e) {
        swan.showToast({title: '暂不支持预览', icon: 'none'});
    }
});

Bug & Tip

  • 文件的临时路径,在智能小程序本次启动期间可以正常使用,如需持久保存,需在主动调用 swan.saveFile,在智能小程序下次启动时才能访问得到。


百度智能小程序 选择图片或使用相机拍照
百度智能小程序 压缩图片接口
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

百度智能小程序开发文档

百度智能小程序 组件

百度智能小程序 地图

百度智能小程序 画布

百度智能小程序 API

百度智能小程序 界面

百度智能小程序 关注小程序引导组件

百度智能小程序 自定义组件

百度智能小程序 媒体

百度智能小程序 设备

百度智能小程序 拨打电话

百度智能小程序 内存警报

百度智能小程序 手机联系人

百度智能小程序 用户截屏事件

百度智能小程序 第三方平台

百度智能小程序 开放接口

百度智能小程序 百度收银支付

百度智能小程序 分包预下载

百度智能小程序 数据分析

百度智能小程序 服务端

百度智能小程序 云开发

百度智能小程序 初始化

百度智能小程序 云函数

百度智能小程序 服务端初始化

百度智能小程序 服务器获取上下文

百度智能小程序 服务端云函数

百度智能小程序 开发教程

百度智能小程序 功能开发

百度智能小程序 基本原理

百度智能小程序 小程序自动化

百度智能小程序 视频教程

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }