前言:在HarmonyOS項目開發中,我們使用Ark-Ts語言開發項目。我們有個功能是拍照,除了正常顯示出來,并且上傳服務器。我在開發過程中,遇到的問題是,如果離開這個頁面再回到當前頁面仍要顯示圖片,那我的思路就是存儲在沙盒,重新回到這個頁面先去沙盒里面查找照片,如果找到就顯示出來。
流程圖:
1.模擬拍照:
模擬拍照方法
takePhoto(){let pixelMap1 = await SnapshotUtil.snapshot()//添加水印信息(此處省略)//調用步驟2.//照片存儲到本地,并返回路徑let filePath:string = await WinPixelImageTool.asyncSavePixelImageToFileCache(waterMarkPixelMap);//存儲照片存儲沙盒路徑let imageKey = '自定義key值'PreferencesManager.set(imageKey,filePath);}
/*** 獲取窗口截圖,使用Promise異步回調。* @param windowClass 不傳默認截圖主窗口* @returns*/static async snapshot(windowClass?: window.Window): Promise<image.PixelMap> {return (windowClass ?? AppUtil.getMainWindow()).snapshot();}
2.生成圖片存儲路徑
static asyncSavePixelImageToFileCache(pixelIamge:PixelMap){return new Promise<string>((resolve)=>{const imagePackerApi: image.ImagePacker = image.createImagePacker();let packOpts : image.PackingOption = { format:"image/png", quality:100 };const context : Context = AppUtil.getContext();let fileName = DateUtil.getTodayTime().toString();let path : string = context.cacheDir + `/sfa`;if (!FileUtil.accessSync(path)) {FileUtil.mkdirSync(path)}path = `${path}/pixel_map_${fileName}.png`let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE);imagePackerApi.packToFile(pixelIamge, file.fd, packOpts,(error: BusinessError): void => {if (error) {resolve('')}else {// let fileUriPath = fileUri.getUriFromPath(path);resolve(path)}})})}
//存儲方法
static set(key: string, value: dataPreferences.ValueType) {if (context==undefined) {context = AppUtil.getContext()}let preferences = dataPreferences.getPreferencesSync(context, { name: preferencesName });preferences?.putSync(key, value);preferences?.flush();}
3.如何將圖片轉為PixelMap并且顯示出來,方法如下:
/*
- 沙盒目錄下的照片轉為image.PixelMap
- imageId是存儲照片沙盒路徑的key
- localImagePath 是照片的存儲沙盒路徑
*/
//通過Imagekey獲取圖片,比如門頭照顯示就是此方法static getImageByImageId(imageId:string):Promise<image.PixelMap> {return new Promise<image.PixelMap>(async (resolve,reject) => {let localImagePath = PreferencesManager.get(imageId) as string;if (localImagePath&&localImagePath.length>0) {let tmpImagePixelMap = await WinImagePixelMapUtils.getImagePixelMapWithFilePath(localImagePath);resolve(tmpImagePixelMap.pixelMap);}else {reject();}})}//WinImagePixelMapUtils類
static async getImagePixelMapWithFilePath(filePath:string){let imageSource = image.createImageSource(filePath);return await imageSource2PixelMap(imageSource);}export async function imageSource2PixelMap(imageSource: image.ImageSource): Promise<ImagePixelMap> {const imageInfo: image.ImageInfo = await imageSource.getImageInfo();const height = imageInfo.size.height;const width = imageInfo.size.width;const options: image.DecodingOptions = {editable: true,desiredSize: { height, width }};const pixelMap: PixelMap = await imageSource.createPixelMap(options);const result: ImagePixelMap = { pixelMap, width, height };return result;
}
getImageByImageId
通過此方法找到沙盒里面的圖片,
使用Image組件可以直接加載tmpImagePixelMap.pixelMap