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 image from '@ohos.multimedia.image' 17import mediaLibrary from '@ohos.multimedia.mediaLibrary' 18import fileio from '@ohos.fileio' 19import prompt from '@ohos.prompt' 20import Logger from '../model/Logger' 21 22const TAG: string = '[MediaUtils]' 23 24export default class MediaUtils { 25 private tag: string = 'MediaUtils' 26 private mediaTest: mediaLibrary.MediaLibrary = undefined 27 28 constructor(context:any){ 29 this.mediaTest = mediaLibrary.getMediaLibrary(context) 30 } 31 32 async createAndGetFile() { 33 let info = { 34 prefix: 'IMG_', suffix: '.jpg', directory: mediaLibrary.DirectoryType.DIR_IMAGE 35 } 36 37 let displayName = `${info.prefix}${info.suffix}` 38 Logger.info(this.tag, `displayName = ${displayName}`) 39 let publicPath = await this.mediaTest.getPublicDirectory(info.directory) 40 return await this.mediaTest.createAsset(mediaLibrary.MediaType.IMAGE, displayName, publicPath) 41 } 42 43 async queryFile(uri: string) { 44 let fetchOp = { 45 selections: '', 46 selectionArgs: [], 47 uri: uri 48 } 49 50 let fileAssetsResult = await this.mediaTest.getFileAssets(fetchOp) 51 Logger.info(TAG, `queryFile fetchFileResult.getCount() = ${fileAssetsResult.getCount()}`) 52 return await fileAssetsResult.getFirstObject() 53 } 54 55 async getPixelMap(uri: string) { 56 Logger.info(this.tag, `getPixelMap, uri = ${uri}`) 57 let file = await this.queryFile(uri) 58 if (file.mediaType === mediaLibrary.MediaType.IMAGE) { 59 let fd = await file.open('r') 60 Logger.info(this.tag, `getPixelMap, fd = ${fd}`) 61 let imageResource = await image.createImageSource(fd) 62 let pixelMap = await imageResource.createPixelMap() 63 await imageResource.release() 64 file.close(fd) 65 return pixelMap 66 } 67 return null 68 } 69 70 async savePicture(data: image.PixelMap) { 71 Logger.info(TAG, `savePicture`) 72 let packOpts: image.PackingOption = { 73 format: "image/jpeg", quality: 100 74 } 75 let imagePackerApi = image.createImagePacker() 76 let arrayBuffer = await imagePackerApi.packing(data, packOpts) 77 let fileAsset = await this.createAndGetFile() 78 let fd = await fileAsset.open('Rw') 79 imagePackerApi.release() 80 await fileio.write(fd, arrayBuffer) 81 await fileAsset.close(fd) 82 Logger.info(TAG, `write done`) 83 prompt.showToast({ 84 message: '图片保存成功', duration: 1000 85 }) 86 } 87} 88