【HarmonyOS Next】图片选择方案

背景


封装一个选择图片和调用拍照相机的按钮,展示api13下选择图片和调用相机,可以使用不申请用户权限的方式,进行图片的选择和修改。但是,目前方案并未包含上传图片保存的功能,仅提供图片选择或者拍照后,图片展示的一种方案。

在这里插入图片描述

项目架构

在这里插入图片描述

  • Common :公共操作类存放文件夹
  • PromptActionClass:全局弹窗操作类
  • components:公共弹窗组件文件夹
  • SelectImageDialog:选择图片弹窗组件
  • pages->Index:入口界面

重要方法解析


调用相机拍照

  • 添加camera, cameraPicker的外部引用
import { camera, cameraPicker } from '@kit.CameraKit';
  • 使用cameraPicker的pick方法实现安全调用设备相机,并返回选择结果cameraPicker.PickerResult对象,通过设置cameraPicker.PickerProfile对象属性实现对相机的初始化属性设置。
try {//配置相机设置let pickerProfile: cameraPicker.PickerProfile = {cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,};let result: cameraPicker.PickerResult =await cameraPicker.pick(getContext(), [cameraPicker.PickerMediaType.PHOTO],pickerProfile);if (result.resultCode == 0) {await this.UpdateShowImage(result.resultUri);}PromptActionClass.CloseDialog();return true;
} catch (e) {console.info(e);return false;
}

访问图库选择图片

  • 添加PromptActionClass的外部引用
import { PromptActionClass } from '../Common/PromptActionClass';
  • 使用photoAccessHelper.PhotoViewPicker对象的select方法,实现安全调用相册并选择图片。通过photoAccessHelper.PhotoSelectOptions对象,对选择方法进行初始化,可以设置默认选择、选择数量、选择类型等。
try {const photoSelectOpt = new photoAccessHelper.PhotoSelectOptions();//设置选择类型photoSelectOpt.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;//选择图片最大数量photoSelectOpt.maxSelectNumber = 1;//图片选择器const photoPicker = new photoAccessHelper.PhotoViewPicker();const selectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(photoSelectOpt)let uri: string = "";if (selectResult.isOriginalPhoto || selectResult.photoUris.length == 0) {return false;}uri = selectResult.photoUris[0];await this.UpdateShowImage(uri);PromptActionClass.CloseDialog();return true;
} catch (e) {console.info(e);return false;
}

整体代码


Index

import { image } from '@kit.ImageKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { PromptActionClass } from '../Common/PromptActionClass';
import { SelectImageDialog } from '../components/SelectImageDialog';
import { camera, cameraPicker } from '@kit.CameraKit';@Entry
@ComponentV2
struct Index {@Local ShowImage: ResourceStr | PixelMap = $r('app.media.AddImageIcon')aboutToAppear(): void {PromptActionClass.SetContext(this.getUIContext());PromptActionClass.SetOptions({builder: () => {this.PictureBuilder()},alignment: DialogAlignment.Bottom,cornerRadius: {topLeft: 20,topRight: 20,bottomLeft: 20,bottomRight: 20},height: 154,width: "90%",})}build() {RelativeContainer() {Button() {Image(this.ShowImage).width("100%").borderRadius(20).padding(10)}.width(120).height(120).type(ButtonType.Normal).backgroundColor(Color.White).borderWidth(3).borderColor('#592708').borderRadius(20).id("AddImageBtn").alignRules({middle: { anchor: "__container__", align: HorizontalAlign.Center }}).margin({ top: 20 }).onClick(() => {PromptActionClass.OpenDialog();})}.height('100%').width('100%')}@BuilderPictureBuilder() {SelectImageDialog({CancelEvent: async () => {try {PromptActionClass.CloseDialog();return true;} catch (e) {console.info(e);return false;}},TakePictureEvent: async () => {try {//配置相机设置let pickerProfile: cameraPicker.PickerProfile = {cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,};let result: cameraPicker.PickerResult =await cameraPicker.pick(getContext(), [cameraPicker.PickerMediaType.PHOTO],pickerProfile);if (result.resultCode == 0) {await this.UpdateShowImage(result.resultUri);}PromptActionClass.CloseDialog();return true;} catch (e) {console.info(e);return false;}},SelectedPictureEvent: async () => {try {const photoSelectOpt = new photoAccessHelper.PhotoSelectOptions();//设置选择类型photoSelectOpt.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;//选择图片最大数量photoSelectOpt.maxSelectNumber = 1;//图片选择器const photoPicker = new photoAccessHelper.PhotoViewPicker();const selectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(photoSelectOpt)let uri: string = "";if (selectResult.isOriginalPhoto || selectResult.photoUris.length == 0) {return false;}uri = selectResult.photoUris[0];await this.UpdateShowImage(uri);PromptActionClass.CloseDialog();return true;} catch (e) {console.info(e);return false;}}})}async UpdateShowImage(uri: string) {let file = fileIo.openSync(uri, fileIo.OpenMode.READ_ONLY)const imageSourceApi = image.createImageSource(file.fd);let map: PixelMap = await imageSourceApi.createPixelMap();this.ShowImage = map;}
}

PromptActionClass

import { promptAction } from "@kit.ArkUI";
import { BusinessError } from "@kit.BasicServicesKit";/*** 弹窗操作类*/
export class PromptActionClass {/***展示界面的ID集合*/private static ShowIDArray: number[] = [];static Context: UIContext;/*** 弹窗界面设置*/static Options: promptAction.CustomDialogOptions;static SetContext(context: UIContext) {PromptActionClass.Context = context;}static SetOptions(options: promptAction.CustomDialogOptions) {PromptActionClass.Options = options;}/*** 弹窗*/static OpenDialog() {if (PromptActionClass.Options) {PromptActionClass.Context.getPromptAction().openCustomDialog(PromptActionClass.Options).then((id: number) => {PromptActionClass.ShowIDArray.push(id);console.info('弹窗已打开')}).catch((error: BusinessError) => {let message = (error as BusinessError).message;let code = (error as BusinessError).code;console.error(`弹窗失败,错误代码是:${code}, message 是 ${message}`);})}}/*** 关闭弹窗*/static CloseDialog() {if (PromptActionClass.ShowIDArray.length != 0) {try {PromptActionClass.Context.getPromptAction().closeCustomDialog(PromptActionClass.ShowIDArray[PromptActionClass.ShowIDArray.length-1])console.info('成功关闭弹窗.')} catch {(error: BusinessError) => {let message = (error as BusinessError).message;let code = (error as BusinessError).code;console.error(`弹窗关闭失败,错误代码:${code}, message 是 ${message}`);}}}}
}

SelectImageDialog

@ComponentV2
export struct SelectImageDialog {@Event TakePictureEvent: () => Promise<boolean> = async () => {return false;}@Event SelectedPictureEvent: () => Promise<boolean> = async () => {return false;}@Event CancelEvent: () => Promise<boolean> = async () => {return false;}build() {RelativeContainer() {Button("拍照").type(ButtonType.Normal).width("100%").id("TakePictureBtn").backgroundColor("#ffffff").height(50).fontColor("#343434").alignRules({bottom: { anchor: "SelectedPictureBtn", align: VerticalAlign.Top }}).onClick(async () => {await this.TakePictureEvent();})Button("从相册中选择").type(ButtonType.Normal).width("100%").height(50).id("SelectedPictureBtn").backgroundColor("#ffffff").fontColor("#343434").borderWidth({ bottom: 2, top: 2 }).borderColor("#f6f6f6").alignRules({center: { anchor: "__container__", align: VerticalAlign.Center }}).onClick(async () => {await this.SelectedPictureEvent();})Button("取消").width("100%").type(ButtonType.Normal).height(50).backgroundColor("#ffffff").fontColor("#aeaeae").alignRules({top: { anchor: "SelectedPictureBtn", align: VerticalAlign.Bottom }}).onClick(async () => {await this.CancelEvent();})}.height("100%").width("100%")}
}

图片资源

从绑定资源中下载

代码文件下载

ImageSelectDemo: 图片选择博客代码

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/19237.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

25年湖南省考报名流程保姆级教程

2025年湖南省考报名马上就要开始啦&#xff01; 有想要参加湖南省考的姐妹们&#xff0c;可以提前了解一下考试报名流程&#xff0c;熟悉考试报名照上传要求&#xff01; 一、考试时间安排 报名时间&#xff1a;2月17日9:00至2月25日 17:00 审核时间&#xff1a;2月17日9:0…

某大型业务系统技术栈介绍【应对面试】

微服务架构【图】 微服务架构【概念】 微服务架构&#xff0c;是一种架构模式&#xff0c;它提倡将单一应用程序划分成一组小的服务&#xff0c;服务之间互相协调、互相配合&#xff0c;为用户提供最终价值。在微服务架构中&#xff0c;服务与服务之间通信时&#xff0c;通常是…

STM32的DMA解释

一句话解释&#xff1a; DMA的特点就是无需CPU的参与就可以直接访问内存&#xff08;可以直接读取内存的数据&#xff0c;也可以直接传数据给内存&#xff09; 这个内存一般指的是片内SRAM、片内Flash 我举个例子&#xff1a; 有一个温度传感器&#xff0c;它以较高的频率&a…

DIN:引入注意力机制的深度学习推荐系统,

实验和完整代码 完整代码实现和jupyter运行&#xff1a;https://github.com/Myolive-Lin/RecSys--deep-learning-recommendation-system/tree/main 引言 在电商与广告推荐场景中&#xff0c;用户兴趣的多样性和动态变化是核心挑战。传统推荐模型&#xff08;如Embedding &…

网页五子棋——用户模块

目录 用户注册 注册时序图 约定前后端交互接口 后端实现 controller 层接口设计 service 层接口设计 dao 层接口设计 全局异常处理 接口测试 前端实现 register.html css common.css register.css js 注册模块测试 用户登录 登录时序图 约定前后端交互接口 …

深度学习04 数据增强、调整学习率

目录 数据增强 常用的数据增强方法 调整学习率 学习率 调整学习率 ​调整学习率的方法 有序调整 等间隔调整 多间隔调整 指数衰减 余弦退火 ​自适应调整 自定义调整 数据增强 数据增强是通过对训练数据进行各种变换&#xff08;如旋转、翻转、裁剪等&#xff09;&am…

Ubuntu22.04 Deepseek-R1本地容器化部署/内网穿透/OPENWEBUI,打造个人AI助手!

1. 前言 本地部署DeepSeek并实现内网穿透&#xff0c;为家庭成员提供强大的AI支持。通过使用Ollama、Docker、OpenWebUI和Nginx&#xff0c;内网穿透&#xff0c;我们可以轻松实现快速响应和实时搜索功能。 2.软硬件环境 系统&#xff1a;ubuntu22.04, cuda12GPU: RTX2080Ti …

DeepSeek与ChatGPT的全面对比

在人工智能&#xff08;AI&#xff09;领域&#xff0c;生成式预训练模型&#xff08;GPT&#xff09;已成为推动技术革新的核心力量。OpenAI的ChatGPT自发布以来&#xff0c;凭借其卓越的自然语言处理能力&#xff0c;迅速占据市场主导地位。然而&#xff0c;近期中国AI初创公…

[HarmonyOS]鸿蒙(添加服务卡片)推荐商品 修改卡片UI(内容)

什么是服务卡片 &#xff1f; 鸿蒙系统中的服务卡片&#xff08;Service Card&#xff09;就是一种轻量级的应用展示形式&#xff0c;它可以让用户在不打开完整应用的情况下&#xff0c;快速访问应用内的特定功能或信息。以下是服务卡片的几个关键点&#xff1a; 轻量级&#…

【数据结构】 栈和队列

在计算机科学的世界里&#xff0c;数据结构是构建高效算法的基础。栈&#xff08;Stack&#xff09;和队列&#xff08;Queue&#xff09;作为两种基本且重要的数据结构&#xff0c;在软件开发、算法设计等众多领域都有着广泛的应用。今天&#xff0c;我们就来深入探讨一下栈和…

「软件设计模式」桥接模式(Bridge Pattern)

深入解析桥接模式&#xff1a;解耦抽象与实现的艺术 一、模式思想&#xff1a;正交维度的优雅解耦 桥接模式&#xff08;Bridge Pattern&#xff09;通过分离抽象&#xff08;Abstraction&#xff09;与实现&#xff08;Implementation&#xff09;&#xff0c;使二者可以独立…

新建github操作

1.在github.com的主页根据提示新建一个depository。 2.配置用户名和邮箱 git config --global user.name "name" git config --global user.email "email" 3.生成ssh秘钥 ssh-keygen -t rsa 找到public key 对应的文件路径 cat /root/.ssh/id_rsa 复制显…

【力扣】108.将有序数组转换为二叉搜索树

AC截图 题目 思路 因为nums数组是严格递增的&#xff0c;所以只需要每次选出中间节点&#xff0c;然后用左边部分构建左子树&#xff0c;用右边部分构建右子树。 代码 /*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* …

如何在 Mac 上解决 Qt Creator 安装后应用程序无法找到的问题

在安装Qt时&#xff0c;遇到了一些问题&#xff0c;尤其是在Mac上安装Qt后&#xff0c;发现Qt Creator没有出现在应用程序中。通过一些搜索和操作&#xff0c;最终解决了问题。以下是详细的记录和解决方法。 1. 安装Qt后未显示Qt Creator 安装完成Qt后&#xff0c;启动应用程…

Spring AI发布!让Java紧跟AI赛道!

1. 序言 在当今技术发展的背景下&#xff0c;人工智能&#xff08;AI&#xff09;已经成为各行各业中不可忽视的重要技术。无论是在互联网公司&#xff0c;还是传统行业&#xff0c;AI技术的应用都在大幅提升效率、降低成本、推动创新。从智能客服到个性化推荐&#xff0c;从语…

数据库脚本MySQL8转MySQL5

由于生产服务器版本上部署的是MySQL5&#xff0c;而开发手里的脚本代码是MySQL8。所以只能降版本了… 升级版本与降级版本脚本转换逻辑一样 MySQL5与MySQL8版本SQL脚本区别 大多数无需调整、主要是字符集与排序规则 MySQL5与MySQL8版本SQL字符集与排序规则 主要操作&…

STM32物联网终端实战:从传感器到云端的低功耗设计

STM32物联网终端实战&#xff1a;从传感器到云端的低功耗设计 一、项目背景与挑战分析 1.1 物联网终端典型需求 &#xff08;示意图说明&#xff1a;传感器数据采集 → 本地处理 → 无线传输 → 云端存储&#xff09; 在工业物联网场景中&#xff0c;终端设备需满足以下核心需…

牛客寒假训练营3

M 牛客传送门 代码如下: const int N2e610,M1e410; const int INF0x3f3f3f3f; const int mod998244353; ll n;void solve(){string s; cin >> s;string ns"nowcoder";sort(s.begin(),s.end(…

BY组态:构建灵活、可扩展的自动化系统

引言 在现代工业自动化领域&#xff0c;BY组态&#xff08;Build Your Own Configuration&#xff09;作为一种灵活、可扩展的解决方案&#xff0c;正逐渐成为工程师和系统集成商的首选。BY组态允许用户根据具体需求自定义系统配置&#xff0c;从而优化生产效率、降低成本并提…

DeepSeek 通过 API 对接第三方客户端 告别“服务器繁忙”

本文首发于只抄博客&#xff0c;欢迎点击原文链接了解更多内容。 前言 上一期分享了如何在本地部署 DeepSeek R1 模型&#xff0c;但通过命令行运行的本地模型&#xff0c;问答的交互也要使用命令行&#xff0c;体验并不是很好。这期分享几个第三方客户端&#xff0c;涵盖了桌…