1/* 2 * Copyright (c) 2023 Hunan OpenValley Digital Industry Development 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 fs from '@ohos.file.fs'; 17import fileIo from '@ohos.file.fs'; 18import { logger } from '../util/Logger'; 19 20const TAG: string = '[Sample_SavePixelMap]'; 21/** 22 * 保存pixelMap,返回路径 23 * @param pm 24 * @returns 25 */ 26export async function savePixelMap(context: Context, pm: PixelMap): Promise<string> { 27 if (pm === null) { 28 logger.error(TAG, '传入的pm为空'); 29 return ''; 30 } 31 const imagePackerApi: image.ImagePacker = image.createImagePacker(); 32 let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 30 }; 33 try { 34 const data: ArrayBuffer = await imagePackerApi.packing(pm, packOpts); 35 return await saveFile(context, data); 36 } catch (err) { 37 logger.error(TAG, '保存文件失败,err=' + JSON.stringify(err)); 38 return ''; 39 } 40} 41 42async function saveFile(context: Context, data: ArrayBuffer): Promise<string> { 43 let uri: string = context.filesDir + '/' + getTimeStr() + '.jpg'; 44 let file: fileIo.File = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); 45 fs.writeSync(file.fd, data); 46 fs.closeSync(file); 47 // /data/storage/.... 加上file://前缀 48 uri = 'file:/' + uri; 49 // 打开媒体文件,存储图片 50 setImageList(uri); 51 return uri; 52} 53 54function setImageList(uri: string) { 55 56 let imageList: Array<string> | undefined = AppStorage.Get('imageList'); 57 const index: number | undefined = AppStorage.Get('selectIndex'); 58 if (imageList !== undefined && index !== undefined) { 59 imageList[index] = uri; 60 } 61 AppStorage.SetOrCreate<Array<string>>('imageList', imageList); 62 63 64} 65 66function getTimeStr() { 67 const now: Date = new Date(); 68 const year: number = now.getFullYear(); 69 const month: number = now.getMonth() + 1; 70 const day: number = now.getDate(); 71 const hours: number = now.getHours(); 72 const minutes: number = now.getMinutes(); 73 const seconds: number = now.getSeconds(); 74 return `${year}${month}${day}_${hours}${minutes}${seconds}`; 75}