?文章的目的為了記錄使用Arkts?進行Harmony?app?開發學習的經歷。本職為嵌入式軟件開發,公司安排開發app,臨時學習,完成app的開發。開發流程和要點有些記憶模糊,趕緊記錄,防止忘記。
??相關鏈接:
開源 Arkts 鴻蒙應用 開發(一)工程文件分析-CSDN博客
開源 Arkts 鴻蒙應用 開發(二)封裝庫.har制作和應用-CSDN博客
開源 Arkts 鴻蒙應用 開發(三)Arkts的介紹-CSDN博客
開源 Arkts 鴻蒙應用 開發(四)布局和常用控件-CSDN博客
開源 Arkts 鴻蒙應用 開發(五)控件組成和復雜控件-CSDN博客
開源 Arkts 鴻蒙應用 開發(六)數據持久--文件和首選項存儲-CSDN博客
開源 Arkts 鴻蒙應用 開發(七)數據持久--sqlite關系數據庫-CSDN博客
開源 Arkts 鴻蒙應用 開發(八)多媒體--相冊和相機-CSDN博客
開源 Arkts 鴻蒙應用 開發(九)通訊--tcp客戶端-CSDN博客
開源 Arkts 鴻蒙應用 開發(十)通訊--Http數據傳輸-CSDN博客
?推薦鏈接:
開源 java android app 開發(一)開發環境的搭建-CSDN博客
開源 java android app 開發(二)工程文件結構-CSDN博客
開源 java android app 開發(三)GUI界面布局和常用組件-CSDN博客
開源 java android app 開發(四)GUI界面重要組件-CSDN博客
開源 java android app 開發(五)文件和數據庫存儲-CSDN博客
開源 java android app 開發(六)多媒體使用-CSDN博客
開源 java android app 開發(七)通訊之Tcp和Http-CSDN博客
開源 java android app 開發(八)通訊之Mqtt和Ble-CSDN博客
開源 java android app 開發(九)后臺之線程和服務-CSDN博客
開源 java android app 開發(十)廣播機制-CSDN博客
開源 java android app 開發(十一)調試、發布-CSDN博客
開源 java android app 開發(十二)封庫.aar-CSDN博客
推薦鏈接:
開源C# .net mvc 開發(一)WEB搭建_c#部署web程序-CSDN博客
開源 C# .net mvc 開發(二)網站快速搭建_c#網站開發-CSDN博客
開源 C# .net mvc 開發(三)WEB內外網訪問(VS發布、IIS配置網站、花生殼外網穿刺訪問)_c# mvc 域名下不可訪問內網,內網下可以訪問域名-CSDN博客
開源 C# .net mvc 開發(四)工程結構、頁面提交以及顯示_c#工程結構-CSDN博客
開源 C# .net mvc 開發(五)常用代碼快速開發_c# mvc開發-CSDN博客
本章內容主要是鴻蒙的多媒體使用,主要功能包括從相冊選擇圖片、拍攝照片以及將圖片保存到應用沙箱目錄。
1.使用流程
2.相冊和相機的使用
3.保存到沙箱
4.所有代碼
5.顯示效果
一、使用流程圖
二、相冊和相機的使用
2.1??使用PhotoViewPicker
選擇圖片
Button("打開相冊照片").width('100%').height(40).onClick(async () => {try {let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;PhotoSelectOptions.maxSelectNumber = 1;let photoPicker = new photoAccessHelper.PhotoViewPicker();photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {this.imageUri = PhotoSelectResult.photoUris[0] ? PhotoSelectResult.photoUris[0] : this.imageUri;hilog.info(0x0000, TAG, 'PhotoViewPicker.select succeed, uri: ' + JSON.stringify(PhotoSelectResult));}).catch((err: BusinessError) => {hilog.error(0x0000, TAG, `PhotoViewPicker.select failed, error: ${err.code}, ${err.message}`);});} catch (error) {let err: BusinessError = error as BusinessError;hilog.error(0x0000, TAG, `PhotoViewPicker failed, error: ${err.code}, ${err.message}`);}this.isShowGet = false;})
2.2??用cameraPicker調用設備相機
Button("相機拍攝照片").width('100%').height(40).onClick(async () => {// [Start pick_file]try {let pickerProfile: cameraPicker.PickerProfile ={ cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK };//Select the action of pulling up the camera to take pictures.let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(this.getUIContext().getHostContext(),[cameraPicker.PickerMediaType.PHOTO], pickerProfile);//Return the photo uri to the application.this.imageUri = pickerResult.resultUri ? pickerResult.resultUri : this.imageUri;hilog.info(0x0000, TAG, 'cameraPicker.pick succeed, uri: ' + JSON.stringify(pickerResult));} catch (error) {let err = error as BusinessError;hilog.error(0x0000, TAG, `cameraPicker.pick failed, error: ${err.code}, ${err.message}`);}// [End pick_file]this.isShowGet = false;})
三、保存到沙箱,特別的是大量使用async/await
處理異步操作
async saveImageToSandbox() {// 1. 檢查圖片URIif (!this.imageUri) {this.getUIContext().getPromptAction().showToast({message: $r('app.string.no_image_alert'),duration: 2000});return;}try {// 2. 等待圖片復制到沙箱await copyImg2Sandbox(this.imageUri, this.path);// 3. 創建ImageSourcethis.imageSource = image.createImageSource(this.path);// 4. 并行獲取圖片信息await Promise.all([new Promise<void>((resolve, reject) => {this.imageSource!.getImageInfo((error, info) => {error ? reject(error) : resolve();});}),this.imageSource.getImageProperties([image.PropertyKey.IMAGE_WIDTH,image.PropertyKey.IMAGE_LENGTH,image.PropertyKey.F_NUMBER])]);// 5. 創建PixelMap(確保這一步成功)this.pixelMap = await this.imageSource.createPixelMap();if (!this.pixelMap) {throw new Error('Failed to create PixelMap');}// 6. 保存到文件await pixelMap2File(this.pixelMap, this.path);this.getUIContext().getPromptAction().showToast({message: $r('app.string.save_in_sandbox_success'),duration: 2000});this.isShowSave = false;} catch (error) {this.handleSaveError(error as BusinessError);}}
四、所有代碼,新建工程后,只修改Index.ets就可以
Index.ets代碼
import { image } from '@kit.ImageKit';
import { PhotoPickerComponent, PickerController, photoAccessHelper, ReminderMode } from '@kit.MediaLibraryKit';
import { cameraPicker, camera } from '@kit.CameraKit';
import { picker } from '@kit.CoreFileKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { copyImg2Sandbox, pixelMap2File } from '../common/utils/Utils';const TAG = 'IMAGE_APP';@Entry
@Component
struct Index {@State path: string = this.getUIContext().getHostContext()!.filesDir + '/image.jpg';@State pixelMapPath: string = this.getUIContext().getHostContext()!.filesDir + '/pixelMap.jpg';@State imageUri: string | undefined = undefined;@State imageSource: image.ImageSource | undefined = undefined;@State pixelMap: image.PixelMap | undefined = undefined;@State isShowGet: boolean = false;@State isShowPicker: boolean = false;@State isShowSave: boolean = false;@State pickerController: PickerController = new PickerController();async saveImageToSandbox() {// 1. 檢查圖片URIif (!this.imageUri) {this.getUIContext().getPromptAction().showToast({message: $r('app.string.no_image_alert'),duration: 2000});return;}try {// 2. 等待圖片復制到沙箱await copyImg2Sandbox(this.imageUri, this.path);// 3. 創建ImageSourcethis.imageSource = image.createImageSource(this.path);// 4. 并行獲取圖片信息await Promise.all([new Promise<void>((resolve, reject) => {this.imageSource!.getImageInfo((error, info) => {error ? reject(error) : resolve();});}),this.imageSource.getImageProperties([image.PropertyKey.IMAGE_WIDTH,image.PropertyKey.IMAGE_LENGTH,image.PropertyKey.F_NUMBER])]);// 5. 創建PixelMap(確保這一步成功)this.pixelMap = await this.imageSource.createPixelMap();if (!this.pixelMap) {throw new Error('Failed to create PixelMap');}// 6. 保存到文件await pixelMap2File(this.pixelMap, this.path);this.getUIContext().getPromptAction().showToast({message: $r('app.string.save_in_sandbox_success'),duration: 2000});this.isShowSave = false;} catch (error) {this.handleSaveError(error as BusinessError);}}// 錯誤處理方法private handleSaveError(error: BusinessError) {hilog.error(0x0000, TAG, `保存失敗: ${error.code}, ${error.message}`);let message = "save_failed";if (error.message.includes('createPixelMap')) {message = "pixelmap_creation_failed";} else if (error.message.includes('copyImg2Sandbox')) {message = "copy_failed";}this.getUIContext().getPromptAction().showToast({message,duration: 2000});}build() {Navigation() {Column() {Image(this.imageUri).height(400).margin({ top: 16 })Column({ space: 12 }) {Button("打開相冊照片").width('100%').height(40).onClick(async () => {try {let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;PhotoSelectOptions.maxSelectNumber = 1;let photoPicker = new photoAccessHelper.PhotoViewPicker();photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {this.imageUri = PhotoSelectResult.photoUris[0] ? PhotoSelectResult.photoUris[0] : this.imageUri;hilog.info(0x0000, TAG, 'PhotoViewPicker.select succeed, uri: ' + JSON.stringify(PhotoSelectResult));}).catch((err: BusinessError) => {hilog.error(0x0000, TAG, `PhotoViewPicker.select failed, error: ${err.code}, ${err.message}`);});} catch (error) {let err: BusinessError = error as BusinessError;hilog.error(0x0000, TAG, `PhotoViewPicker failed, error: ${err.code}, ${err.message}`);}this.isShowGet = false;})Button("相機拍攝照片").width('100%').height(40).onClick(async () => {// [Start pick_file]try {let pickerProfile: cameraPicker.PickerProfile ={ cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK };//Select the action of pulling up the camera to take pictures.let pickerResult: cameraPicker.PickerResult = await cameraPicker.pick(this.getUIContext().getHostContext(),[cameraPicker.PickerMediaType.PHOTO], pickerProfile);//Return the photo uri to the application.this.imageUri = pickerResult.resultUri ? pickerResult.resultUri : this.imageUri;hilog.info(0x0000, TAG, 'cameraPicker.pick succeed, uri: ' + JSON.stringify(pickerResult));} catch (error) {let err = error as BusinessError;hilog.error(0x0000, TAG, `cameraPicker.pick failed, error: ${err.code}, ${err.message}`);}// [End pick_file]this.isShowGet = false;})Button("保存照片到APP目錄").width('100%').height(40).onClick(async () => {this.saveImageToSandbox();})}.width('100%').height(150).padding({ left: 16, right: 16 }).margin({ bottom: 16 }).justifyContent(FlexAlign.SpaceBetween)}.width('100%').height('100%').justifyContent(FlexAlign.SpaceBetween)}.width('100%').height('100%').title($r('app.string.title'))}
}
五、顯示效果
5.1? app圖片和打開相冊后圖片
5.2? 保存到APP目錄后圖片所存位置圖,點擊DevEco的右下角的 Device File Browser