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 */ 15import image from '@ohos.multimedia.image' 16import fileio from '@ohos.fileio' 17import prompt from '@ohos.prompt' 18import mediaLibrary from '@ohos.multimedia.mediaLibrary' 19import DateTimeUtil from '../model/DateTimeUtil' 20import Logger from '../model/Logger' 21 22const TAG: string = '[MediaUtils]' 23 24class MediaUtils { 25 async createAndGetFile(context: any) { 26 let mediaTest = mediaLibrary.getMediaLibrary(context) 27 let info = { 28 prefix: 'IMG_', suffix: '.jpg', directory: mediaLibrary.DirectoryType.DIR_IMAGE 29 } 30 let dateTimeUtil = new DateTimeUtil() 31 let name = `${dateTimeUtil.getDate()}_${dateTimeUtil.getTime()}` 32 let displayName = `${info.prefix}${name}${info.suffix}` 33 let publicPath = await mediaTest.getPublicDirectory(info.directory) 34 Logger.info(TAG, `publicPath = ${publicPath}`) 35 return await mediaTest.createAsset(mediaLibrary.MediaType.IMAGE, displayName, publicPath) 36 } 37 38 async savePicture(data: image.PixelMap, context: any) { 39 Logger.info(TAG, `savePicture`) 40 let packOpts: image.PackingOption = { 41 format: "image/jpeg", quality: 100 42 } 43 let imagePackerApi = image.createImagePacker() 44 let arrayBuffer = await imagePackerApi.packing(data, packOpts) 45 let fileAsset = await this.createAndGetFile(context) 46 let fd = await fileAsset.open('Rw') 47 imagePackerApi.release() 48 try { 49 await fileio.write(fd, arrayBuffer) 50 } catch (err) { 51 Logger.error(`write failed, code is ${err.code}, message is ${err.message}`) 52 } 53 await fileAsset.close(fd) 54 Logger.info(TAG, `write done`) 55 prompt.showToast({ 56 message: '图片保存成功', duration: 1000 57 }) 58 } 59} 60 61export default new MediaUtils()