HarmonyOS NEXT开发实战教程:选择相册和拍照
今天的内容是介绍在鸿蒙开发中从相册选择照片,和调用相机拍照,并使用这两个功能实现朋友圈编辑页面。

这部分内容没什么好废话的,都是固定用法,直接上代码。
首先添加权限:
ohos.permission.CAMERA
选择相册:
async getAlbum() {
const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
photoSelectOptions.maxSelectNumber = 5; // 选择媒体文件的最大数目
let uris: Array<string> = [];
const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
uris = photoSelectResult.photoUris;
uris.forEach(element => {
this.photoList.push(element)
});
console.info('photoViewPicker.select to file succeed and uris are:' + uris);
}).catch((err: BusinessError) => {
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
}
调用相机:
async invokeCamera(callback: (uri: string) => void) {
try {
let pickerProfile: cameraPicker.PickerProfile = {
cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
};
let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(getContext(),
[cameraPicker.PickerMediaType.PHOTO, cameraPicker.PickerMediaType.VIDEO], pickerProfile);
console.log("the pick pickerResult is:" + JSON.stringify(pickerResult));
if (callback && pickerResult) {
callback(pickerResult.resultUri);
}
} catch (error) {
let err = error as BusinessError;
console.error(`the pick call failed. error code: ${err.code}`);
}
}
整个页面完整代码如下:
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { cameraPicker } from '@kit.CameraKit';
import { camera } from '@kit.CameraKit';
import { AlertSheet } from './AlertSheet';
@Entry
@Component
struct Index {
@State photoList:string[] = []
dialogController: CustomDialogController | null = new CustomDialogController({
builder: AlertSheet({titles:['拍照','相册'],itemClick:(str)=>{
switch (str){
case '拍照':
this.invokeCamera((url)=>{
this.photoList.push(url)
})
break;
case '相册':
this.getAlbum()
break;
}
}}),
alignment: DialogAlignment.Bottom,
offset: { dx: 0, dy: -25 }
})
async getAlbum() {
const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 过滤选择媒体文件类型为IMAGE
photoSelectOptions.maxSelectNumber = 5; // 选择媒体文件的最大数目
let uris: Array<string> = [];
const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
uris = photoSelectResult.photoUris;
uris.forEach(element => {
this.photoList.push(element)
});
console.info('photoViewPicker.select to file succeed and uris are:' + uris);
}).catch((err: BusinessError) => {
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
}
async invokeCamera(callback: (uri: string) => void) {
try {
let pickerProfile: cameraPicker.PickerProfile = {
cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK
};
let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(getContext(),
[cameraPicker.PickerMediaType.PHOTO, cameraPicker.PickerMediaType.VIDEO], pickerProfile);
console.log("the pick pickerResult is:" + JSON.stringify(pickerResult));
if (callback && pickerResult) {
callback(pickerResult.resultUri);
}
} catch (error) {
let err = error as BusinessError;
console.error(`the pick call failed. error code: ${err.code}`);
}
}
build() {
Column(){
TextArea({placeholder:'这一刻的想法'})
.placeholderFont({size:16})
.placeholderColor('rgb(188,188,188)')
.width('100%')
.height(100)
.backgroundColor(Color.White)
Grid(){
ForEach(this.photoList,(str:string,index)=>{
GridItem(){
Image(str)
.width(90)
.height(90)
}
})
GridItem(){
Image($r('app.media.add'))
.width(90)
.height(90)
.onClick(()=>{
this.dialogController?.open()
})
}
}
.columnsGap(10)
.rowsGap(10)
.columnsTemplate('1fr 1fr 1fr 1fr')
}
.padding({left:15,right:15,top:40})
}
}
HarmonyOS NEXT开发实战教程:选择相册和拍照的更多相关文章
- asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发2-Model层建立
上篇(asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发1-准备工作)文章讲解了开发过程中的准备工作,主要创建了项目数据库及项目,本文主要讲解项目M层的实现,M层这里 ...
- 微信小程序-云开发实战教程
微信小程序-云开发实战教程 云函数,云存储,云数据库,云调用 https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/gettin ...
- Swift游戏开发实战教程(霸内部信息大学)
Swift游戏开发实战教程(大学霸内部资料) 试读下载地址:http://pan.baidu.com/s/1sj7DvQH 介绍:本教程是国内第一本Swift游戏开发专向资料. 本教程具体解说记忆配对 ...
- asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发4- 后台模板html页面创建
上一篇教程<asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发3-登录模块开发>完成了本项目的登录模块,登录后就需要进入后台管理首页了,需要准备一个后台模 ...
- Python开发实战教程(8)-向网页提交获取数据
来这里找志同道合的小伙伴!↑↑↑ Python应用现在如火如荼,应用范围很广.因其效率高开发迅速的优势,快速进入编程语言排行榜前几名.本系列文章致力于可以全面系统的介绍Python语言开发知识和相关知 ...
- React Native Android原生模块开发实战|教程|心得|怎样创建React Native Android原生模块
尊重版权,未经授权不得转载 本文出自:贾鹏辉的技术博客(http://blog.csdn.net/fengyuzhengfan/article/details/54691503) 告诉大家一个好消息. ...
- asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发3-登录模块开发
进行本文之前需要在数据库用户表里面增加一条用户数据,直接手动添加即可,未安全考虑密码一定要使用Md5加密后的,这里提供666666的Md5密文为(c831b04de153469d),本文完成登录模块的 ...
- asp.net mvc+jquery easyui开发实战教程之网站后台管理系统开发1-准备工作
/****** Object: 新闻表 Script Date: 2017/9/2 星期六 15:11:12 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENT ...
- php扩展开发实战教程(1)
我的开发环境: Ubuntu16.04 apt方式安装的php5.6, apache,mysql等 由于我的本机用的是apt方式安装的php,所以我这里从头开始用最精简的方式,编译安装一个php5.4 ...
- HTML5 App商业开发实战教程 基于WeX5可视化开发平台
随机推荐
- Windows系统安装Ollama超简教程(附DeepSeek R1实战)
一.Ollama下载指引 官网地址:https://ollama.com/download 选择Windows版本直接下载(推荐64位系统),安装包745MB左右,支持Win10/11系统.点击&qu ...
- 【整活向】把tidb的文档塞给了基于oceanbase的RAG机器人
最近官方推出了免费试用365天的云数据库,版本也升级到了4.3.支持了向量功能. 官方推出了活动体验AI的动手实战活动, 教程中使用了docker单机版数据库,既然有免费的云数据库,就优先使用云数据库 ...
- "最新"部署幻兽帕鲁游戏服务器及开局经验分享
Banner 2024,<幻兽帕鲁><雾锁王国>等游戏爆火!那么如何快速拥有一个可以跟小伙伴们愉快玩耍的服务器呢?社区里不少小伙伴已经给出了自己的最佳实践,你甚至不需要懂技术, ...
- @Scheduled参数及cron表达式解释
@Scheduled支持以下8个参数:1.cron:表达式,指定任务在特定时间执行:2.fixedDelay:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms:3.fixedDela ...
- 【IDEA】IDEA上如何解决代码冲突
首先,坐好准备工作,在feature-resolve-conflict分支上作如下改动: 在master分支作如下改动: 假如现在我们需要将master分支合并到feature-resolve-con ...
- Landsat遥感影像分幅条带介绍与矢量下载:WRS的Path与Row
本文介绍Landsat系列卫星的分幅规则,并提供WRS的矢量文件下载. WRS,即Worldwide Reference System,是Landsat系列卫星全球影像标记符号系统,用以区分全 ...
- 多机器的键鼠互通——Synergy/Deskflow配置记录
Synergy (1.14.6) 情况一样,那么感觉就是机器之间TCP连接有问题,测试不同 一些测试命令 ss -tlnp | grep 24800 # 查看端口情况 sudo lsof -i :24 ...
- 【P5】Verilog搭建流水线MIPS-CPU
课下 Thinking_Log 1.为何不允许直接转发功能部件的输出 直接转发会使一些组合逻辑部件增加新的长短不一的操作延迟,不利于计算设置流水线是时钟频率(保证流水线吞吐量?). 2.jal中将NP ...
- linux ln命令详解
介绍 ln是linux的一个重要命令,它的功能是为某一个文件在另外一个位置建立一个同步的链接.当我们需要在不同的目录,用到相同的文件时,我们不需要在每一个需要的目录下都放一个必须相同的文件,我们只要在 ...
- SQL INSERT批量插入方式
1.常规INSERT写法 INSERT INTO ... VALUES (...); INSERT INTO 表名( `字段1`, `字段2`) VALUES ('字段1的值', '字段2的值') ...