1、权限申请

    "requestPermissions": [{"name": "ohos.permission.CAMERA","reason": "$string:reason_camera","usedScene": {"abilities": ["EntryAbility"]}},{"name": "ohos.permission.MEDIA_LOCATION","reason": "$string:reason_media_location","usedScene": {"abilities": ["EntryAbility"]}}]

2、ui实现

import { dataSharePredicates } from '@kit.ArkData';
import { abilityAccessCtrl, Permissions } from '@kit.AbilityKit';
import { camera } from '@kit.CameraKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { filePreview } from '@kit.PreviewKit';
import { cameraShooting, capture, getUriAsync, previewPhoto, setPhotoFlashMode } from '../utils/CameraShooter';
import display from '@ohos.display';
import { AppStorageV2, curves } from '@kit.ArkUI';
import { sensor } from '@kit.SensorServiceKit';
import { DegreeConstants } from '../constants/DegreeConstants'let cameraPosition = 0;
let surfaceId = '';
let context = getContext(this);@Entry
@ComponentV2
struct XComponentPage {mXComponentController: XComponentController = new XComponentController;permissions: Array<Permissions> = ['ohos.permission.CAMERA','ohos.permission.MEDIA_LOCATION',];@Local cameraMargin: number = 40@Local cameraHeight: number = 2560@Local isRatio: boolean = true; // true: 16 / 9@Local isFront: boolean = false;@Local photoUri: string | Resource | PixelMap = ''@Local isStabilization: boolean = false;@Local isMovingPhoto: boolean = false;@Local flashPic: ResourceStr = ''textTimerController: TextTimerController = new TextTimerController();@Local rotation: number = 0;@Local moreTools: ResourceStr[] = ['相册', '拍照', '拍视频']@BuilderbottomKeystrokeBuilder() {// 底部拍照翻转相机Row() {Image(this.photoUri).borderWidth(this.photoUri === '' ? 0 : 1).borderColor(Color.White).height(70).width(70).borderRadius(35).rotate({ angle: this.rotation }).animation({ curve: curves.springMotion() }).onClick(() => {if (this.photoUri !== '') {previewPhoto(context);}})// 拍照Column() {Column() {}.width(60).height(60).backgroundColor('#0FD7B8').borderRadius(30)}.width(72).height(72).border({ width: 3, color: Color.White }).borderRadius(36).justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center).onClick(() => {capture(this.isFront);getUriAsync().then(photoUri => {// photoUri 就是你要的图片uri// 可以赋值给 @State/@Local 变量,UI自动刷新this.photoUri = photoUri;console.log('hlasdlkas===' + this.photoUri)});})Column() {Text('翻转').width(28).onClick(async () => {cameraPosition = cameraPosition === 1 ? 0 : 1cameraShooting(cameraPosition, surfaceId, context, this.isRatio);this.Initialize();this.isFront = cameraPosition !== 0;})}.height(70).width(70).justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center)}.margin({ top: 20 }).width('100%').justifyContent(FlexAlign.SpaceAround).margin({ bottom: 39 })}@BuilderproportionBuilder() {Row({ space: 20 }) {Text('1:1').height(30).onClick(() => {this.cameraMargin = 100this.cameraHeight = 1440this.isRatio = falsecameraShooting(cameraPosition, surfaceId, context, this.isRatio);this.Initialize();})Text('9:16').height(30).onClick(() => {this.cameraHeight = 2560this.cameraMargin = 40this.isRatio = truecameraShooting(cameraPosition, surfaceId, context, this.isRatio);this.Initialize();})}.margin({ top: 500 })}onPageShow(): void {filePreview.closePreview(context);}async aboutToAppear() {sensor.on(sensor.SensorId.GRAVITY, (data: sensor.GravityResponse) => {let degree: number = -1;degree = this.getCalDegree(data.x, data.y, data.z);if (degree >= 0 && (degree <= DegreeConstants.DEGREE_ONE || degree >= DegreeConstants.DEGREE_FOUR)) {this.rotation = camera.ImageRotation.ROTATION_0;} else if (degree >= DegreeConstants.DEGREE_ONE && degree <= DegreeConstants.DEGREE_TWO) {this.rotation = camera.ImageRotation.ROTATION_270;} else if (degree >= DegreeConstants.DEGREE_TWO && degree <= DegreeConstants.DEGREE_THREE) {this.rotation = camera.ImageRotation.ROTATION_180;} else if (degree >= DegreeConstants.DEGREE_THREE && degree <= DegreeConstants.DEGREE_FOUR) {this.rotation = camera.ImageRotation.ROTATION_90;}})abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context, this.permissions).then(() => {setTimeout(async () => {await cameraShooting(cameraPosition, surfaceId, context, this.isRatio);}, 200);});}aboutToDisappear(): void {sensor.off(sensor.SensorId.GRAVITY);}getCalDegree(x: number, y: number, z: number): number {let degree: number = -1;if ((x * x + y * y) * 3 < z * z) {return degree;}degree = 90 - (Number)(Math.round(Math.atan2(y, -x) / Math.PI * 180));return degree >= 0 ? degree % 360 : degree % 360 + 360;}build() {Stack({ alignContent: Alignment.Top }) {XComponent({ type: XComponentType.SURFACE, controller: this.mXComponentController }).onLoad(async () => {// todo:切换比例,暂时用不到if (this.isRatio === true) {this.mXComponentController.setXComponentSurfaceRect({surfaceWidth: display.getDefaultDisplaySync().width,surfaceHeight: display.getDefaultDisplaySync().width * 16 / 9,offsetY: 0});surfaceId = this.mXComponentController.getXComponentSurfaceId();} else {this.mXComponentController.setXComponentSurfaceRect({surfaceWidth: display.getDefaultDisplaySync().width,surfaceHeight: display.getDefaultDisplaySync().width,});surfaceId = this.mXComponentController.getXComponentSurfaceId();}}).width(px2vp(1440)).height(px2vp(this.cameraHeight)).align(Alignment.Top)Column() {Column() {Row() {Text('x').width(24)Text('拍照').fontWeight(600)Text().width(24)}.width('100%').justifyContent(FlexAlign.SpaceBetween)//比例this.proportionBuilder()// 底部按键this.bottomKeystrokeBuilder()}.width('100%').height(px2vp(display.getDefaultDisplaySync().width * 16 / 9) - 10).justifyContent(FlexAlign.SpaceBetween)// 更多Row() {ForEach(this.moreTools, (item: ResourceStr, index: number) => {Text(item)})}.width('70%').layoutWeight(1).justifyContent(FlexAlign.SpaceBetween).alignItems(VerticalAlign.Center)}.height('100%').align(Alignment.Top).padding({ left: 14, right: 14, top: 10 })}.height('100%').width('100%').backgroundColor(Color.White).padding({ top: 50 }) //顶部安全区}Initialize(): void {this.isStabilization = false;this.isMovingPhoto = false;if (this.isRatio === true) {this.mXComponentController.setXComponentSurfaceRect({surfaceWidth: display.getDefaultDisplaySync().width,surfaceHeight: display.getDefaultDisplaySync().width * 16 / 9, offsetY: 0})} else {this.mXComponentController.setXComponentSurfaceRect({surfaceWidth: display.getDefaultDisplaySync().width,surfaceHeight: display.getDefaultDisplaySync().width})}}switchFlash(flashMode: number): void {setPhotoFlashMode(flashMode);}async getThumbnail(): Promise<void> {let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();predicates.orderByDesc(photoAccessHelper.PhotoKeys.DATE_ADDED);let fetchOptions: photoAccessHelper.FetchOptions = {fetchColumns: [],predicates: predicates};let photoHelper = photoAccessHelper.getPhotoAccessHelper(context);let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> =await photoHelper.getAssets(fetchOptions);if (fetchResult !== undefined) {let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();this.photoUri = await photoAsset.getThumbnail();}}
}

3、工具

import { camera } from '@kit.CameraKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { common } from '@kit.AbilityKit';
import { AppStorageV2, display } from '@kit.ArkUI';
import { colorSpaceManager } from '@kit.ArkGraphics2D';let previewOutput: camera.PreviewOutput;
let cameraInput: camera.CameraInput;
let photoSession: camera.PhotoSession;
let photoOutPut: camera.PhotoOutput;
let currentContext: Context;
let uri: string;
let uriWaiters: ((uri: string) => void)[] = [];export async function cameraShooting(cameraPosition: number, surfaceId: string, context: Context, ratio: boolean):Promise<number[]> {currentContext = context;releaseCamera();let cameraManager: camera.CameraManager = camera.getCameraManager(context);if (!cameraManager) {return [];}let cameraArray: camera.CameraDevice[] = cameraManager.getSupportedCameras();if (cameraArray.length <= 0) {return [];}cameraInput = cameraManager.createCameraInput(cameraArray[cameraPosition]);await cameraInput.open();let sceneModes: camera.SceneMode[] = cameraManager.getSupportedSceneModes(cameraArray[cameraPosition]);let cameraOutputCap: camera.CameraOutputCapability =cameraManager.getSupportedOutputCapability(cameraArray[cameraPosition], camera.SceneMode.NORMAL_PHOTO);let isSupportPhotoMode: boolean = sceneModes.indexOf(camera.SceneMode.NORMAL_PHOTO) >= 0;if (!isSupportPhotoMode) {return [];}if (!cameraOutputCap) {return [];}let previewProfilesArray: camera.Profile[] = cameraOutputCap.previewProfiles;let photoProfilesArray: camera.Profile[] = cameraOutputCap.photoProfiles;let previewProfile: undefined | camera.Profile = previewProfilesArray.find((profile: camera.Profile) => {let screen = display.getDefaultDisplaySync();if (screen.width <= 1080) {if (ratio === true) {return profile.size.height === 1080 && profile.size.width === 1920;} else {return profile.size.height === 1080 && profile.size.width === 1080;}} else {if (ratio === true) {return profile.size.height === 1440 && profile.size.width === 2560;} else {return profile.size.height === 1440 && profile.size.width === 1440;}}});let photoProfile: undefined | camera.Profile = photoProfilesArray.find((profile: camera.Profile) => {if (previewProfile) {return profile.size.width <= 4096 && profile.size.width >= 2448;}return undefined;});previewOutput = cameraManager.createPreviewOutput(previewProfile, surfaceId);if (previewOutput === undefined) {return [];}photoOutPut = cameraManager.createPhotoOutput(photoProfile);if (photoOutPut === undefined) {return [];}// Save PicturesetPhotoOutputCb(photoOutPut);photoSession = cameraManager.createSession(camera.SceneMode.NORMAL_PHOTO) as camera.PhotoSession;if (photoSession === undefined) {return [];}photoSession.beginConfig();photoSession.addInput(cameraInput);photoSession.addOutput(previewOutput);photoSession.addOutput(photoOutPut);photoSession.setColorSpace(colorSpaceManager.ColorSpace.DISPLAY_P3);await photoSession.commitConfig();await photoSession.start();let flashStatus: boolean = photoSession.hasFlash();if (flashStatus) {photoSession.setFlashMode(camera.FlashMode.FLASH_MODE_CLOSE);}let focusModeStatus: boolean = photoSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);if (focusModeStatus) {photoSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO);}let zoomRatioRange = photoSession.getZoomRatioRange();return zoomRatioRange;
}export function capture(isFront: boolean): void {let settings: camera.PhotoCaptureSetting = {quality: camera.QualityLevel.QUALITY_LEVEL_HIGH,rotation: camera.ImageRotation.ROTATION_0,mirror: isFront};photoOutPut.capture(settings);
}export async function setPhotoFlashMode(flashMode: number): Promise<void> {photoSession.setFlashMode(flashMode);
}export async function releaseCamera(): Promise<void> {if (photoSession) {photoSession.stop();}if (cameraInput) {cameraInput.close();}if (previewOutput) {previewOutput.release();}if (photoSession) {photoSession.release();}if (photoOutPut) {photoOutPut.release();}
}function setPhotoOutputCb(photoOutput: camera.PhotoOutput): void {photoOutput.on('photoAssetAvailable',async (_err: BusinessError, photoAsset: photoAccessHelper.PhotoAsset): Promise<void> => {let accessHelper: photoAccessHelper.PhotoAccessHelper =photoAccessHelper.getPhotoAccessHelper(currentContext);let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest =new photoAccessHelper.MediaAssetChangeRequest(photoAsset);assetChangeRequest.saveCameraPhoto();await accessHelper.applyChanges(assetChangeRequest);uri = photoAsset.uri;// AppStorage.setOrCreate('photoUri', await photoAsset.getThumbnail());uriWaiters.forEach(fn => fn(uri));uriWaiters = [];});
}export function getUriAsync(): Promise<string> {return new Promise(resolve => {uriWaiters.push(resolve);});
}export function previewPhoto(context: Context): void {let photoContext = context as common.UIAbilityContext;photoContext.startAbility({parameters: { uri: uri },action: 'ohos.want.action.viewData',bundleName: 'com.huawei.hmos.photos',abilityName: 'com.huawei.hmos.photos.MainAbility'})
}

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

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

相关文章

greenplum7.2并行备份及恢复

1.并行备份 pg_dump -Fd --gp-syntax -U gpadmin -p 5432 -h 172.19.0.2 -d postgres -j 4 -f /opt/greenplum/data/postgres_backup_$(date %Y-%m-%d) 参数 含义 -Fd 使用 directory 格式&#xff08;支持并行&#xff09; --gp-syntax 使用 Greenplum 特定语法&#xff08;…

备赛2025年初中古诗文大会:练习历年真题,吃透知识点(0703)

初中古诗文大会的比赛内容古诗词、文言文各占比50%左右&#xff0c;从历年的比赛来看&#xff0c;中考语文的古诗文部分&#xff08;35分&#xff09;涉及到的古诗词、文言文知识点都在初中古诗文大会中考过。这些知识点掌握了&#xff0c;对于将来高中、高考也有直接的帮助。 …

BRAKER:真核微生物cds和蛋白注释

https://github.com/Gaius-Augustus/BRAKER 安装 # 第一次打开会pull这个docker docker run --user 1000:100 --rm -it teambraker/braker3:latest bash bash /opt/BRAKER/example/docker-tests/test3.sh braker.gtf&#xff1a;BRAKER 的最终基因集。 braker.codingseq&am…

基于 Three.js 与 WebGL 的商场全景 VR 导航系统源码级解析

本文面向Web前端开发者、WebGL/Three.js 爱好者、对VR/AR应用开发感兴趣的技术人员、智慧商场解决方案开发者。详细介绍如何利用 WebGL (Three.js框架) 构建高性能的商场全景VR环境&#xff0c;并实现精准的室内定位与3D路径规划导航功能。 如需获取商场全景VR导航系统解决方案…

AWS CloudFormation部署双可用区VPC网络架构 - 完整指南

一、模板概述 本CloudFormation模板用于在AWS上快速部署一个高可用的双可用区VPC网络架构,包含公有子网和私有子网。该架构是构建云原生应用的基础,特别适合生产环境使用。 二、完整模板代码 AWSTemplateFormatVersion: 2010-09-09 Description: Customizable dual-AZ VPC…

2025汽车声学升级:高透音汽车喇叭网成高端车型新标配

随着消费者对车载音质和静谧性要求的提升&#xff0c;高透音汽车喇叭网正成为高端车型的差异化配置。传统冲压金属网因声学损耗大、设计单一逐渐被淘汰&#xff0c;而新一代蚀刻工艺通过微孔结构优化&#xff0c;实现了声学性能与美学设计的双重突破。以下是技术趋势与市场前景…

决策树(Decision tree)算法详解(ID3、C4.5、CART)

文章目录 一、决策树介绍1.1 决策树的结构特征1.2 决策树的构建三步骤1.3 决策树构建例子 二、ID3决策树&#xff1a;基于信息增益的决策模型2.1 信息增益的公式与符号解析2.2 信息增益的意义2.3 ID3决策树案例演示&#xff1a;贷款申请分类2.4 ID3决策树缺陷 三、C4.5决策树&a…

python基础-网络的TCP、UDP协议操作

1.tcp基本语法 # ### TCP协议 客户端 import socket # 1.创建一个socket对象 sk socket.socket() # 2.与服务端建立连接 sk.connect( ("127.0.0.1" , 9000) ) # 3.收发数据的逻辑 """发送的数据类型是二进制字节流""" ""&q…

基于spark的航班价格分析预测及可视化

基于spark的航班价格分析预测及可视化 项目概况 [&#x1f447;&#x1f447;&#x1f447;&#x1f447;&#x1f447;&#x1f447;&#x1f447;&#x1f447;] 点这里,查看所有项目 [&#x1f446;&#x1f446;&#x1f446;&#x1f446;&#x1f446;&#x1f446;&…

每日算法刷题Day41 6.28:leetcode前缀和2道题,用时1h20min(要加快)

5. 523.连续的子数组和(中等,学习) 523. 连续的子数组和 - 力扣&#xff08;LeetCode&#xff09; 思想 1.给你一个整数数组 nums 和一个整数 k &#xff0c;如果 nums 有一个 好的子数组 返回 true &#xff0c;否则返回 false&#xff1a; 一个 好的子数组 是&#xff1a;…

拉取vue-element-admin

这个错误表明 npm 在尝试通过 SSH 克隆 GitHub 仓库时遇到了权限问题&#xff0c;根本原因是系统无法正确处理中文用户名路径下的 SSH 配置。以下是详细的解决方案&#xff1a; 解决方案 1&#xff1a;使用 HTTPS 代替 SSH&#xff08;推荐&#xff09; 修改 Git 全局配置&…

c语言的数组注意事项

在C语言中&#xff0c;int()[5]和int是两种完全不同的指针类型&#xff0c;理解它们的区别对于正确处理数组和多维数组至关重要。下面详细解释&#xff1a; 1&#xff1a;int*&#xff08;指向整型的指针&#xff09; 含义&#xff1a;指向单个int类型数据的指针典型用法&…

在 NestJS 中优雅使用 TypeORM 进行事务管理

事务管理是数据库操作中至关重要的部分&#xff0c;它能确保一系列操作要么全部成功&#xff0c;要么全部失败。本文将详细介绍在 NestJS 框架中使用 TypeORM 进行事务管理的多种方法。 为什么需要事务管理&#xff1f; 想象一下银行转账场景&#xff1a;从一个账户扣款后&am…

给任意apk内容添加水印

1 有源码给app添加水印 使用java可以适配更多的apk&#xff0c;如果使用koltin一些老的apk就会有适配问题 通过registerActivityLifecycleCallbacks拿到activity对象设置水印 在application里面registerActivityLifecycleCallbacks就行 static class MyActivityLifecycleCallb…

扩展的Fortran在高性能计算(HPC)中助力有限元分析(FEA)、流体力学(CFD)、结构力学、复合材料和增材制造仿真的详细指南【附完整示例代码实现】

Fortran 在高性能计算(HPC)中的仿真应用 本指南深入探讨 Fortran 语言如何在高性能计算(HPC)中助力有限元分析(FEA)、流体力学(CFD)、结构力学、复合材料和增材制造仿真。每部分详细介绍,分析 Fortran 的优势、应用场景和实现细节,并附带完整的 Fortran 模拟代码(含…

Java 大视界 -- Java 大数据机器学习模型在自然语言处理中的跨语言信息检索与知识融合(331)

Java 大视界 -- Java 大数据机器学习模型在自然语言处理中的跨语言信息检索与知识融合&#xff08;331&#xff09; 引言&#xff1a;正文&#xff1a;一、Java 驱动的多语言数据处理平台1.1 分布式多语言语料智能清洗系统1.2 多语言文本分布式存储与索引优化1.3 低资源语言数据…

[2025CVPR]SEEN-DA:基于语义熵引导的领域感知注意力机制

目录 引言 研究背景 方法介绍 核心思想 语义熵&#xff08;Semantic Entropy&#xff09; 语义熵引导的注意力机制 领域感知注意力模块 实验设计 数据集 实现细节 结果与分析 对比实验结果 消融实验 代码实现 结论 引言 领域自适应目标检测&#xff08;Domain …

你的RAG系统安全么?

生成式人工智能&#xff08;GenAI&#xff09;近年来发展迅速&#xff0c;大语言模型成为这一浪潮的核心力量。无论是商业还是开源模型&#xff0c;它们都具备强大的语言理解与生成能力&#xff0c;正广泛应用于内容创作、聊天机器人等场景&#xff0c;让企业更容易落地智能应用…

【2.3 漫画SpringSecurity - 守护应用安全的钢铁卫士】

🔐 漫画SpringSecurity - 守护应用安全的钢铁卫士 📚 目录 记忆口诀可视化图表形象比喻数字记忆实战案例记忆卡片总结诗句面试准备🎪 记忆口诀 🏗️ SpringSecurity核心 - “认证授权过滤链” 认证Authentication确身份,用户名密码验证真 授权Authorization控权限,…

ModbusRTU转Profinet网关在电子天平与PLC系统集成中的应用

ModbusRTU转Profinet网关在电子天平与PLC系统集成中的应用 工业自动化场景中&#xff0c;设备通信协议差异常成为系统集成的隐形壁垒。某精密制造企业近期遇到的奥豪斯电子天平与西门子PLC通讯难题&#xff0c;正是这一矛盾的典型缩影。奥豪斯天平采用ModbusRTU协议&#xff0…