前言
保存圖片功能幾乎是每個(gè)應(yīng)用程序必備的功能之一,當(dāng)用戶遇到喜歡的圖片時(shí)可以保存到手機(jī)相冊(cè)。那么在鴻蒙中保存圖片是否也需要申請(qǐng)用戶存儲(chǔ)權(quán)限以及如何將圖片保存到相冊(cè),本文將詳細(xì)講述怎么保存網(wǎng)絡(luò)圖片,指定布局生成圖片保存至相冊(cè)的功能實(shí)現(xiàn)。
實(shí)現(xiàn)效果
需求分析
一般在 Android 或 iOS 上保存圖片都需要申請(qǐng)應(yīng)用存儲(chǔ)權(quán)限,否則將禁止訪問應(yīng)用存儲(chǔ),不能保存圖片到磁盤中。在鴻蒙系統(tǒng)中當(dāng)然也有存儲(chǔ)權(quán)限,但是鴻蒙系統(tǒng)對(duì)于權(quán)限管理十分嚴(yán)格,一般情況下,禁止用戶申請(qǐng)?jiān)L問存儲(chǔ)權(quán)限。但是提供了系統(tǒng)級(jí)別的安全控件,不需要用戶手動(dòng)申請(qǐng)權(quán)限,用于存儲(chǔ)的直接訪問。
- 可以使用系統(tǒng)提供的安全控件實(shí)現(xiàn)權(quán)限的直接訪問。
- 同時(shí)也提供申請(qǐng)權(quán)限方式進(jìn)行存儲(chǔ)權(quán)限的訪問。
- 使用網(wǎng)絡(luò)請(qǐng)求將圖片轉(zhuǎn)成流,然后保存成圖片。
技術(shù)實(shí)現(xiàn)
申請(qǐng)權(quán)限方式
- 權(quán)限申請(qǐng)
const permissions: Array< Permissions > = [
'ohos.permission.WRITE_IMAGEVIDEO'
];
const context = getContext(this) as common.UIAbilityContext;
const atManager = abilityAccessCtrl.createAtManager();
await atManager.requestPermissionsFromUser(context, permissions);
- 權(quán)限判斷
PermissionUtil.checkAccessToken(permissions[0]).then((status)= >{
if (status == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
FileSaveManager.getPicture(this.imagePath)
}else{
PermissionUtil.openPermissionsInSystemSettings(getContext(this) as common.UIAbilityContext)
}
})
安全控件方式
SaveButton({ text: SaveDescription.SAVE_IMAGE, buttonType: ButtonType.Normal })
.fontColor(Color.White)
.fontWeight(FontWeight.Medium)
.onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) = > {
if (result == SaveButtonOnClickResult.SUCCESS) {
try {
this.saveImage()
} catch (error) {
console.error("error is " + JSON.stringify(error));
}
}
})
可以看出通過系統(tǒng)安全控件 SaveButton 可以臨時(shí)訪問系統(tǒng)存儲(chǔ),不需要申請(qǐng)任何權(quán)限。更好的保護(hù)用戶隱私安全,這也是鴻蒙官方提倡使用的方式。
網(wǎng)絡(luò)圖片保存
- 下載圖片,并將數(shù)據(jù)轉(zhuǎn)化為 ArrayBuffer 類型。
/**
* 通過http的request方法從網(wǎng)絡(luò)下載圖片資源
*/
static async getPicture(url:string) {
http.createHttp()
.request(url,
(error: Error, data: http.HttpResponse) = > {
if (error) {
showShortCenterToast("圖片保存失敗")
return;
}
// 判斷網(wǎng)絡(luò)獲取到的資源是否為ArrayBuffer類型
if (data.result instanceof ArrayBuffer) {
FileSaveManager.saveImageToPhoto(data.result as ArrayBuffer)
}
}
)
}
- 保存圖片到相冊(cè)
/**
* 保存ArrayBuffer到圖庫
* @param buffer:圖片ArrayBuffer
* @returns
*/
static async saveImageToPhoto(buffer: ArrayBuffer | string): Promise< void > {
const context = getContext() as common.UIAbilityContext; // 獲取getPhotoAccessHelper需要的context
const helper = photoAccessHelper.getPhotoAccessHelper(context); // 獲取相冊(cè)管理模塊的實(shí)例
const uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg'); // 指定待創(chuàng)建的文件類型、后綴和創(chuàng)建選項(xiàng),創(chuàng)建圖片或視頻資源
const file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
let r = await fs.write(file.fd, buffer);
await fs.close(file.fd);
showShortCenterToast("圖片保存成功")
}
指定布局保存
在 Android 或 iOS 中,經(jīng)常會(huì)遇到需要保存指定樣式的布 View 為圖片。Android 中則需要使用 View 的繪制,將布局繪制出來后,再進(jìn)行保存。但是在鴻蒙中實(shí)現(xiàn)起來就比較簡(jiǎn)單。
** 1. 將需要保存的 View 布局指定 Id。**
Column() {
//布局樣式
}
.id("root")
- 通過 id 將 View 保存成圖片。
componentSnapshot.get("photo", (error: Error, pixmap: image.PixelMap) = > {
if (error) {
console.log("error: " + JSON.stringify(error))
return;
}
const packOpts : image.PackingOption = { format:"image/jpeg", quality:98 };
imagePackerApi.packing(pixmap, packOpts).then( async (data : ArrayBuffer) = > {
FileSaveManager.saveImageToPhoto(data)
}).catch((error : BusinessError) = > {
console.error('Failed to pack the image. And the error is: ' + error);
})
})
總結(jié)
對(duì)比 Android 或 iOS 來說,鴻蒙在實(shí)現(xiàn)功能上相對(duì)簡(jiǎn)單,比較容易上手。但是鴻蒙對(duì)于用戶權(quán)限的獲取要求比較嚴(yán)格,正式上線一般都需要使用系統(tǒng)提供的安全組件訪問應(yīng)用程序的相冊(cè)或存儲(chǔ),日常開發(fā)中需要十分注意,以免影響項(xiàng)目的正常上線。
-
Android
+關(guān)注
關(guān)注
12文章
3971瀏覽量
129883 -
鴻蒙系統(tǒng)
+關(guān)注
關(guān)注
183文章
2642瀏覽量
67887 -
HarmonyOS
+關(guān)注
關(guān)注
80文章
2146瀏覽量
32493
發(fā)布評(píng)論請(qǐng)先 登錄
harmony-utils之PickerUtil,拍照、文件選擇和保存,工具類
鴻蒙5開發(fā)寶藏案例分享---AI輔助圖文內(nèi)容高效編創(chuàng)
HarmonyOS實(shí)戰(zhàn):一招解決等待多個(gè)并發(fā)結(jié)果

鴻蒙5開發(fā)寶藏案例分享---一多開發(fā)實(shí)例(圖片美化)
本地服務(wù)器部署怎么選?一招搞定企業(yè)IT成本、性能與安全問題!

移動(dòng)電源EMC整改:認(rèn)證失敗到一次通過的實(shí)戰(zhàn)經(jīng)驗(yàn)

鴻蒙開發(fā)實(shí)現(xiàn)圖片上傳(上傳用戶頭像)
基于STM32F103RC的電子相冊(cè)(原理圖、PCB源文件、程序源碼及制作)
爬蟲數(shù)據(jù)獲取實(shí)戰(zhàn)指南:從入門到高效采集
瓶蓋產(chǎn)線效率低、廢品多?阿童木 900E 一招搞定

一招治“浮”! 高精度3D線激光輪廓測(cè)量?jī)x保障螺絲裝配

存儲(chǔ)空間告急?NAS擴(kuò)容一招搞定,輕松無憂!

Air780E模組LuatOS開發(fā)實(shí)戰(zhàn) —— 手把手教你搞定數(shù)據(jù)打包解包

A0到A4的圖框只要一個(gè)圖紙模板就搞定了?

基于ArkTS語言的OpenHarmony APP應(yīng)用開發(fā):圖片處理

評(píng)論