1/* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import photoAccessHelper from '@ohos.file.photoAccessHelper'; 17import common from '@ohos.app.ability.common'; 18import { LogUtil } from '../baseUtil/LogUtil'; 19 20const TAG: string = 'MediaLibraryAccess'; 21 22interface albumType { 23 count: number; 24 obj: photoAccessHelper.PhotoAsset | null; 25} 26 27export class MediaLibraryAccess { 28 static async getFirstObject(fetchOpt: photoAccessHelper.FetchOptions, context: common.UIAbilityContext) { 29 let album: albumType = { 30 count: 0, 31 obj: null, 32 } 33 try { 34 // 通过Uri拷贝图片到指定指定的包路径下 35 // 1、获取本地路径 36 37 let fileResult = await photoAccessHelper.getPhotoAccessHelper(context).getAssets(fetchOpt) 38 if (fileResult != undefined) { 39 album.count = fileResult.getCount(); 40 if (album.count <= 0) { 41 return album; 42 } 43 44 let file = await fileResult.getFirstObject(); 45 if (file) { 46 album.obj = file; 47 return album; 48 } else { 49 LogUtil.warn(TAG, 'Failed getFirstObject') 50 } 51 } 52 return album; 53 } 54 catch (error) { 55 LogUtil.error(TAG, `getFirstObject loadData error: ${error}`) 56 return album; 57 } 58 } 59 60 static async openAsset(mode: string, fileAsset: photoAccessHelper.PhotoAsset) { 61 LogUtil.info(TAG, 'openAsset start') 62 let fd = await fileAsset.open(mode); 63 LogUtil.info(TAG, `openAsset end. fd: ${fd}`) 64 65 if (fd <= 0) { 66 LogUtil.warn(TAG, 'openAsset Fail') 67 return; 68 } 69 70 return fd; 71 } 72 73 static async closeAsset(fd: number, fileAsset: photoAccessHelper.PhotoAsset) { 74 LogUtil.info(TAG, 'closeAsset start') 75 76 if (fd <= 0) { 77 LogUtil.warn(TAG, 'closeAsset fd is invalid') 78 return; 79 } 80 81 try { 82 await fileAsset.close(fd) 83 LogUtil.info(TAG, 'closeAsset end') 84 85 } catch (error) { 86 LogUtil.warn(TAG, 'closeAsset fail') 87 } 88 } 89}