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 {LogUtil} from '../baseUtil/LogUtil' 17import MediaLib from '@ohos.multimedia.mediaLibrary'; 18 19const TAG = "MediaLibraryAccess" 20export class MediaLibraryAccess { 21 22 static async getFirstObject(fetchOpt, context) { 23 let album = { 24 count: 0, 25 obj: null, 26 } 27 try { 28 // 通过Uri拷贝图片到指定指定的包路径下 29 // 1、获取本地路径 30 31 let fileResult = await MediaLib.getMediaLibrary(context).getFileAssets(fetchOpt) 32 if (fileResult != undefined) { 33 album.count = fileResult.getCount(); 34 if (album.count <= 0) { 35 return album; 36 } 37 38 let file = await fileResult.getFirstObject(); 39 if (file) { 40 album.obj = file; 41 return album; 42 } else { 43 LogUtil.warn(TAG, 'Failed getFirstObject') 44 } 45 } 46 return album; 47 } 48 catch (error) { 49 LogUtil.error(TAG, `getFirstObject loadData error: ${error}`) 50 return album; 51 } 52 } 53 54 static async openAsset(mode: string, fileAsset: any) { 55 LogUtil.info(TAG, 'openAsset start') 56 let fd = await fileAsset.open(mode); 57 LogUtil.info(TAG, `openAsset end. fd: ${fd}`) 58 59 if (fd <= 0) { 60 LogUtil.warn(TAG, 'openAsset Fail') 61 return; 62 } 63 64 return fd; 65 } 66 67 static async closeAsset(fd: number, fileAsset: any) { 68 LogUtil.info(TAG, 'closeAsset start') 69 70 if (fd <= 0) { 71 LogUtil.warn(TAG, 'closeAsset fd is invalid') 72 return; 73 } 74 75 try { 76 await fileAsset.close(fd) 77 LogUtil.info(TAG, 'closeAsset end') 78 79 } catch (error) { 80 LogUtil.warn(TAG, 'closeAsset fail') 81 } 82 } 83}