• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023-2024 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';
19import ndkTest from 'libentry.so'
20import resourceManager from '@ohos.resourceManager';
21
22const TAG: string = '[Sample_SavePixelMap]';
23/**
24 * 保存pixelMap,返回路径
25 * @param pm
26 * @returns
27 */
28export async function savePixelMap(context: Context, pm: PixelMap): Promise<string> {
29  if (pm === null) {
30    logger.error(TAG, '传入的pm为空');
31    return '';
32  }
33  const imagePackerApi: image.ImagePacker = image.createImagePacker();
34  let packOpts: image.PackingOption = { format: 'image/jpeg', quality: 30 };
35  try {
36    packToFile(context, pm);
37    const data: ArrayBuffer = await imagePackerApi.packing(pm, packOpts);
38    // PixelMap转为data
39    packToDataPixelMap(context, data)
40    return await saveFile(context, data);
41  } catch (err) {
42    logger.error(TAG, '保存文件失败,err=' + JSON.stringify(err));
43    return '';
44  }
45}
46
47async function packToFile(context: Context, pixelMap: PixelMap) {
48  let fPath: string = context.cacheDir + '/' + getTimeStr() + '.jpg';
49  let writeFd: fs.File = await fs.open(fPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);
50
51  let opts : image.PackingOption = { format: "image/jpeg", quality: 100};
52  const imagePacker = image.createImagePacker();
53  await imagePacker.packToFile(pixelMap, writeFd.fd, opts);
54  fs.closeSync(writeFd.fd);
55}
56
57async function saveFile(context: Context, data: ArrayBuffer): Promise<string> {
58  let uri: string = context.filesDir + '/' + getTimeStr() + '.jpg';
59  let file: fileIo.File = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
60  fs.writeSync(file.fd, data);
61  // ImageSource转为file
62  packToFileImageSource(context, file);
63  // PixelMap转为file
64  packToFilePixelMap(context, uri);
65  // ImageSource转为data
66  packToDataImageSource(context);
67  fs.closeSync(file);
68  // /data/storage/....  加上file://前缀
69  uri = 'file:/' + uri;
70  // 打开媒体文件,存储图片
71  setImageList(uri);
72  return uri;
73}
74
75function setImageList(uri: string) {
76
77  let imageList: Array<string> | undefined = AppStorage.get('imageList');
78  const index: number | undefined = AppStorage.get('selectIndex');
79  if (imageList !== undefined && index !== undefined) {
80    imageList[index] = uri;
81  }
82  AppStorage.setOrCreate<Array<string>>('imageList', imageList);
83
84
85}
86
87function getTimeStr() {
88  const now: Date = new Date();
89  const year: number = now.getFullYear();
90  const month: number = now.getMonth() + 1;
91  const day: number = now.getDate();
92  const hours: number = now.getHours();
93  const minutes: number = now.getMinutes();
94  const seconds: number = now.getSeconds();
95  return `${year}${month}${day}_${hours}${minutes}${seconds}`;
96}
97
98/**
99 * PixelMap转为file
100 * @param context
101 * @param filePath 调用uri创建ImageSource方法, 需接收filePath参数
102 */
103function packToFilePixelMap(context: Context, filePath: string){
104  try {
105    const packFilePath: string = context.filesDir + '/' + getTimeStr() + '_1.png';
106    const packFile = fs.openSync(packFilePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
107    const result: number = ndkTest.packPixelMapToFile(filePath, packFile.fd)
108    logger.info(TAG, 'packPixelMapToFile result ' + result);
109  } catch (error) {
110    logger.error(TAG, 'packing fail ' + JSON.stringify(error));
111  }
112}
113
114/**
115 * ImageSource转为file
116 * @param context
117 * @param file 调用fd创建ImageSource方法, 需接收file参数
118 */
119function packToFileImageSource(context: Context, file: fileIo.File){
120  try {
121    const packFilePath: string = context.filesDir + '/' + getTimeStr() + '_2.jpg'
122    const packFile = fs.openSync(packFilePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
123    const result: number = ndkTest.packToFileImageSource(file.fd, packFile.fd)
124    logger.info(TAG, 'packToFileImageSource result ' + result);
125  } catch (error) {
126    logger.error(TAG, 'packing fail ' + JSON.stringify(error));
127  }
128}
129
130/**
131 * PixelMap转为data
132 * @param context
133 * @param buffer 调用data创建ImageSource方法, 需接收buffer参数
134 */
135function packToDataPixelMap(context: Context, buffer :ArrayBuffer){
136  try {
137    const packFilePath: string = context.filesDir + '/' + getTimeStr() + '_3.jpg'
138    const result: number = ndkTest.packToDataPixelMap(buffer, packFilePath)
139    logger.info(TAG, 'packToDataPixelMap result ' + result);
140  } catch (error) {
141    logger.error(TAG, 'packing fail ' + JSON.stringify(error));
142  }
143}
144
145/**
146 * ImageSource转为数据
147 * @param context 调用rawFile创建ImageSource方法
148 */
149async function packToDataImageSource(context: Context){
150  try {
151    // rawFile创建ImageSource
152    const resourceMgr = context.createModuleContext('entry').resourceManager
153    let rawFileDescriptor: resourceManager.RawFileDescriptor
154    rawFileDescriptor = await resourceMgr.getRawFd('test_jpg.jpg');
155    const packFilePath: string = context.filesDir + '/' + getTimeStr() + '_4.webp'
156
157    const result: number = ndkTest.packToDataImageSource(rawFileDescriptor.fd, rawFileDescriptor.offset,
158      rawFileDescriptor.length, packFilePath)
159    logger.info(TAG, 'packToDataImageSource result ' + result);
160  } catch (error) {
161    logger.error(TAG, 'packing fail ' + JSON.stringify(error));
162  }
163}