新闻详情

新闻详情

首页 / 资讯中心 / 详情

高校周边通 · 国庆特别版:HarmonyOS 7 文搜图「一日一景」功能开发实战

发布时间:2026/9/30 4:47:35来源:尧图网络
高校周边通 · 国庆特别版:HarmonyOS 7 文搜图「一日一景」功能开发实战
高校周边通 · 国庆特别版HarmonyOS 7 文搜图「一日一景」功能开发实战本文代码基于 HarmonyOS 7 / API 26 Beta2 官方文档中的原始示例撰写函数名、字段名、错误码均来自官网最新版本更新时间2026-09-07。官方原文链接textSearchImage API Reference通过文本搜索图片 开发指南项目背景「高校周边通」是面向大学生的校园本地生活应用。2026 年国庆版本v3.6.0新增「一日一景」功能用户在校园随手拍的国庆元素照片红旗、校门灯笼、社团彩旗等可被端侧 AI 自动建索引用户只要输入一句话就能从相册里翻出对应照片。本文将完整解析该功能背后的textSearchImage实现。一、为什么高校周边通要在国庆版本接入文搜图国庆七天长假是大学生最活跃的拍摄期迎新晚会、社团彩排、宿舍团建、city walk 打卡……用户相册会在一周内新增数百张照片。但翻照片的痛点随之而来“那天食堂门口挂的红灯笼在哪张图里”“国庆晚会我和室友的合影是哪一张”传统按时间线、文件夹浏览效率极低。「一日一景」通过textSearchImage让用户用一句话搜照片整个过程在端侧完成零云端流量零隐私泄露风险。二、textSearchImage官方完整接口接口说明textSearchImage.init(): Promiseboolean初始化分析器textSearchImage.release(): Promisevoid释放分析器textSearchImage.insertImage(imagePath: string, scope: string): Promiseboolean将单张图片特征插入 scopetextSearchImage.search(query: string, scope: string, topKey: number): PromiseImageObject[]在 scope 内检索textSearchImage.deleteImage(imagePath: string, scope: string): Promiseboolean删除单张图片特征textSearchImage.clearData(): Promiseboolean清空所有 scopeImageObject 字段imagePath: string // 图片路径 scope: string // 图片作用域 similarity: number // 相似度 [-1, 1]越大越相似官方错误码1013100001Invalid image path.1013100002Service abnormal.1013100003The capability has been updated. Please use the new API.三、「一日一景」功能完整实现3.1 模块权限配置// module.json5 { module: { requestPermissions: [ { name: ohos.permission.READ_IMAGEVIDEO } ] } }3.2 索引管理服务一日一景核心模块/** * file DaySceneIndexService.ets * description 高校周边通 · 一日一景 索引服务 */import{textSearchImage}fromkit.CoreVisionKit;import{hilog}fromkit.PerformanceAnalysisKit;import{BusinessError}fromkit.BasicServicesKit;import{photoAccessHelper}fromkit.MediaLibraryKit;import{fileIo}fromkit.CoreFileKit;constDOMAIN0x0000;constTAGDaySceneIndex;// 索引域按国庆 高校维度隔离方便节后清理constSCOPE_DAY_SCENEcampus.explorer.dayscene.2026nationalday;exportinterfaceDaySceneHit{imagePath:string;scope:string;similarity:number;}exportclassDaySceneIndexService{/** * 应用启动时调用Ability onCreate */staticasyncinit():Promisevoid{try{constokawaittextSearchImage.init();hilog.info(DOMAIN,TAG,Text search image initialization result:${ok});}catch(error){hilog.error(DOMAIN,TAG,Init failed. Code:${error.code}, message:${error.message});}}/** * 应用退出时调用 */staticasyncrelease():Promisevoid{try{awaittextSearchImage.release();hilog.info(DOMAIN,TAG,Text search image released successfully);}catch(error){hilog.error(DOMAIN,TAG,Release failed. Code:${error.code}, message:${error.message});}}/** * 将相册中的国庆专题照片批量索引 * param photoUris 用户从 photoPicker 选择的 uri 列表 */staticasyncbatchIndex(photoUris:string[]):Promisenumber{letsuccessCount0;for(consturiofphotoUris){// 1. uri 转真实路径官方要求必须是沙箱路径长度 [1,128]constrealPathawaitDaySceneIndexService.uriToPath(uri);if(!realPath)continue;// 2. 调官方 insertImagetry{constresultawaittextSearchImage.insertImage(realPath,SCOPE_DAY_SCENE);if(result)successCount;hilog.info(DOMAIN,TAG,Insert${realPath}:${result});}catch(error){consterrerrorasBusinessError;hilog.warn(DOMAIN,TAG,Insert failed. Code:${err.code}, message:${err.message});}}returnsuccessCount;}/** * 一日一景 - 语义搜索入口 * 用户输入操场上的五星红旗、食堂门口的灯笼 */staticasyncsearch(query:string,topKey:number30):PromiseDaySceneHit[]{try{constresultsawaittextSearchImage.search(query,SCOPE_DAY_SCENE,topKey);hilog.info(DOMAIN,TAG,Search ${query} count:${results.length});returnresults.map(item({imagePath:item.imagePath,scope:item.scope,similarity:item.similarity}));}catch(error){consterrerrorasBusinessError;hilog.error(DOMAIN,TAG,Search failed. Code:${err.code}, message:${err.message});return[];}}/** * 删除某张图片索引用户在相册中删除时同步触发 */staticasyncdelete(imagePath:string):Promiseboolean{try{constresultawaittextSearchImage.deleteImage(imagePath,SCOPE_DAY_SCENE);hilog.info(DOMAIN,TAG,Delete${imagePath}:${result});returnresult;}catch(error){consterrerrorasBusinessError;hilog.warn(DOMAIN,TAG,Delete failed. Code:${err.code}, message:${err.message});returnfalse;}}/** * 国庆结束后清理索引 */staticasyncclearAll():Promiseboolean{try{constresultawaittextSearchImage.clearData();hilog.info(DOMAIN,TAG,Clear all data:${result});returnresult;}catch(error){consterrerrorasBusinessError;hilog.error(DOMAIN,TAG,Clear failed. Code:${err.code}, message:${err.message});returnfalse;}}/** * photoAccessHelper uri 转沙箱路径 */privatestaticasyncuriToPath(uri:string):Promisestring|null{try{constfileawaitfileIo.open(uri,fileIo.OpenMode.READ_ONLY);constpathfileIo.getFilePathFromUri(file.fd);awaitfileIo.close(file);returnpath;}catch{returnnull;}}}3.3 UI 层国庆主题搜索页/** * file DayScenePage.ets * description 高校周边通 · 一日一景 搜索页 */import{photoAccessHelper}fromkit.MediaLibraryKit;import{DaySceneIndexService,DaySceneHit}from../utils/DaySceneIndexService;EntryComponentstruct DayScenePage{Statequery:string;Statehits:DaySceneHit[][];StateindexedCount:number0;// 国庆快捷检索词privatereadonlyholidayPresets:string[][校园里的五星红旗,食堂门口的灯笼,宿舍阳台的烟花,操场的迎新晚会,校门外的国庆彩旗];asyncaboutToAppear():Promisevoid{awaitDaySceneIndexService.init();}asyncaboutToDisappear():Promisevoid{awaitDaySceneIndexService.release();}build(){Column(){// 国庆 BannerRow(){Text(一日一景 · 国庆特辑).fontSize(20).fontWeight(FontWeight.Bold).fontColor(#FFFFE600)Image($r(app.media.national_flag)).width(24).height(24)}.width(100%).padding(16).linearGradient({angle:90,colors:[[#FFE60019,0.0],[#FFFF0000,1.0]]})// 一键索引按钮Button( 从相册导入国庆照片).width(90%).height(48).backgroundColor(#FFE60019).fontColor(Color.White).margin({top:16}).onClick(async(){constpickernewphotoAccessHelper.PhotoViewPicker();constoptsnewphotoAccessHelper.PhotoSelectOptions();opts.MIMETypephotoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;opts.maxSelectNumber50;constresultawaitpicker.select(opts);constcountawaitDaySceneIndexService.batchIndex(result.photoUris);this.indexedCountcount;})// 索引结果if(this.indexedCount0){Text(已索引${this.indexedCount}张国庆照片).fontSize(12).fontColor(#999999).margin({top:8})}// 搜索框Row(){TextInput({placeholder:搜一句灯笼 / 红旗 / 烟花…}).layoutWeight(1).height(40).backgroundColor(#F5F5F5).onChange((v:string){this.queryv;})Button(搜索).height(40).backgroundColor(#FFE60019).onClick(()this.doSearch())}.padding(16)// 国庆快捷词Flex({wrap:FlexWrap.Wrap}){ForEach(this.holidayPresets,(preset:string){Text(#${preset}).fontSize(12).fontColor(#FFE60019).backgroundColor(#22E60019).padding(8).borderRadius(16).margin(4).onClick((){this.querypreset;this.doSearch();})})}.padding({left:16,right:16})// 命中结果Grid(){ForEach(this.hits,(hit:DaySceneHit){GridItem(){Stack(){Image(file://${hit.imagePath}).objectFit(ImageFit.Cover).width(100%).height(140)Text(${(hit.similarity*100).toFixed(0)}%).fontColor(Color.White).fontSize(11).backgroundColor(#99000000).padding(4).borderRadius(4)}}})}.columnsTemplate(1fr 1fr).columnsGap(8).rowsGap(8).padding(16).layoutWeight(1)}.width(100%).height(100%).backgroundColor(#FFFFFF)}privateasyncdoSearch(){if(!this.query.trim())return;this.hitsawaitDaySceneIndexService.search(this.query,30);}}四、节后运营策略textSearchImage.clearData()会清空所有 scope所以在节后建议// 国庆结束 7 天后自动清理索引aboutToDisappear(){if(this.isNationalDayEnded()){DaySceneIndexService.clearAll();}}也可以保留索引但提示用户「索引已过期是否清理」把选择权交给用户。五、写在最后「一日一景」是textSearchImage在 HarmonyOS 7 上的典型落地场景。它把 AI 搜索能力下沉到端侧让学生在节日期间既能快速翻照片又不用担心隐私泄露。这正是 HarmonyOS 7 强调的Local-first AI理念的最好实践。
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

数字政府大模型AI公共支撑平台落地指南:架构、选型与调优 2026/9/30 5:43:46

数字政府大模型AI公共支撑平台落地指南:架构、选型与调优

简介:这是一份面向数字政府与智慧政务建设者、方案规划人员的演示文稿,聚焦大模型人工智能公共支撑平台在政务办公场景中的落地路径。内容从政策驱动与效能瓶颈切入,剖析数据孤岛、智能水平不足、响应滞后等问题,并系统阐述分层技…

阅读更多 →
自养Agent日志:5.9GB模型如何只占2.7GB显存? 2026/9/30 5:43:46

自养Agent日志:5.9GB模型如何只占2.7GB显存?

自养Agent日志:5.9GB的模型只占了2.7GB显存最近在折腾自养的Agent项目,遇到一个很典型的尴尬场景:调好的模型权重有5.9GB,本地显卡显存却只给到8GB,系统一开机就在后台吃掉了将近1GB,真正能用来跑推理的连7…

阅读更多 →
Dify实战指南:从安装部署到知识库工作流与报错排查 2026/9/30 5:43:46

Dify实战指南:从安装部署到知识库工作流与报错排查

前阵子帮朋友公司搞内部知识库问答机器人,选型阶段被问得最多的就是一句话:Dify到底是什么,好不好装,装完又能干嘛。这个问题我回答过很多次,但每次都没法三句讲完,因为它不是一个聊天框工具,而…

阅读更多 →
Dify本地部署全攻略:从环境准备到知识库与工作流实战 2026/9/30 5:43:34

Dify本地部署全攻略:从环境准备到知识库与工作流实战

1. Dify 是什么:拆开揉碎讲清楚过去一年我折腾了不少 AI 应用开发的东西,从最早的手搓 Prompt 调 OpenAI API,到后来用 LangChain 拼链条,再到各种低代码平台,走了挺多弯路。直到用了 Dify,我才有一种“终于…

阅读更多 →
Jev 决策型 Agent 实战:绕过 Token 生成直接输出动作 2026/9/30 5:43:34

Jev 决策型 Agent 实战:绕过 Token 生成直接输出动作

1. 从 Token 到决策:Jev 到底在解决什么问题第一次看到“Jev:当 AI 不再生成 Token,而是直接做决策”这个标题,我脑子里蹦出来的第一个画面是:过去两年我们跟大模型打交道,本质上都在做一件事——猜下一个 …

阅读更多 →
【优化求解】遗传算法创建蜘蛛姿态步态运动【含Matlab源码 15992期】 2026/9/30 5:43:33

【优化求解】遗传算法创建蜘蛛姿态步态运动【含Matlab源码 15992期】

💥💥💥💥💥💥💥💥💞💞💞💞💞💞💞💞💞Matlab武动乾坤博客之家💞…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉