HarmonyOS 鸿蒙Next如何保存网络图片到相册

发布于 1周前 作者 sinazl 最后一次编辑是 5天前 来自 鸿蒙OS

HarmonyOS 鸿蒙Next如何保存网络图片到相册

在模块级module.json5中申明权限

“requestPermissions”: [
{
“name”: ‘ohos.permission.INTERNET’,
“usedScene”: {
“abilities”: [
“EntryAbility”
],
“when”: “inuse”
},
“reason”: “$string:reason”
},
{
“name”: “ohos.permission.WRITE_IMAGEVIDEO”,
“usedScene”: {
“abilities”: [
“EntryAbility”
],
“when”: “inuse”
},
“reason”: “$string:reason”
},

创建如下页面

import { http } from ‘@kit.NetworkKit’
import { BusinessError } from ‘@kit.BasicServicesKit’;
import { photoAccessHelper } from ‘@kit.MediaLibraryKit’;
import { fileIo } from ‘@kit.CoreFileKit’;
import { abilityAccessCtrl, PermissionRequestResult, Permissions, bundleManager, common } from ‘@kit.AbilityKit’;

@Entry
@Component
struct Index {
private PERMISSIONS: Array<Permissions> = [‘ohos.permission.INTERNET’, “ohos.permission.WRITE_IMAGEVIDEO”];
@State str:string = ‘’


async grantPermission(): Promise<boolean> {
try {
let bundleInfo: bundleManager.BundleInfo =
await bundleManager.getBundleInfoForSelf(
bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION
);
let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo;
let tokenId = appInfo.accessTokenId;
let atManager = abilityAccessCtrl.createAtManager();
let pems: Array<Permissions> = [];
for (let i = 0; i < this.PERMISSIONS.length; i++) {
let state = await atManager.checkAccessToken(tokenId, this.PERMISSIONS[i]);
if (state !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
pems.push(this.PERMISSIONS[i]);
}
}
if (pems.length > 0) {
let ctx = getContext(this) as common.UIAbilityContext
let result: PermissionRequestResult = await atManager.requestPermissionsFromUser(ctx, pems);
let grantStatus: Array<number> = result.authResults;
let length: number = grantStatus.length;
for (let i = 0; i < length; i++) {
if (grantStatus[i] !== 0) {
return false;
}
}
}
return true;
} catch (error) {
return false;
}
}


loadImageWithUrl(url: string) {
// 使用request下载图片并在回调函数中保存图片到相册
http.createHttp().request(url,
{
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000
},
async (error: BusinessError, data: http.HttpResponse) => {
if (error) {
console.error(http reqeust failed <span class="hljs-keyword"><span class="hljs-keyword">with</span></span>. Code: ${error.code}, message: ${error.message});
} else {
if (http.ResponseCode.OK === data.responseCode) {
let imageBuffer: ArrayBuffer = data.result as ArrayBuffer;
try {
// 获取相册路径
const context = getContext(this);
let helper = photoAccessHelper.getPhotoAccessHelper(context);
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, ‘jpg’)
let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
// 写入文件
await fileIo.write(file.fd, imageBuffer);
// 关闭文件
await fileIo.close(file.fd);
} catch (error) {
console.error("error is " + JSON.stringify(error))
}
} else {
console.error(“error occurred when image downloaded!”)
}
}
})
}


async aboutToAppear() {
await this.grantPermission().then(async () => {
}).catch((err: BusinessError) => {
console.info(grantPermission faild ${<span class="hljs-built_in"><span class="hljs-built_in">JSON</span></span>.stringify(err.code)});
})
}


build() {
Row() {
Column() {
TextInput({text:this.str, placeholder: ‘输入图片地址’})
.onChange((value: string) => {
this.str = value
})
Button(‘保存图片’)
.onClick(() => {
this.loadImageWithUrl(this.str)
})
}
.width(‘100%’)
}
.height(‘100%’)
}
2 回复

楼主你好,这个普通是不是需要SaveButton,不然权限好像是system的啊

在HarmonyOS鸿蒙Next中保存网络图片到相册,可以通过以下步骤实现:

  1. 下载图片:首先,通过HTTP请求从网络下载图片,并将其存储在应用的临时或持久化存储中,通常是沙箱存储。
  2. 获取图片路径:确保你知道下载后图片的URI或路径,这是后续步骤的关键。
  3. 保存到相册:使用HarmonyOS提供的photoAccessHelper API来创建图片资产,并通过文件系统API(如fs.openfs.write)将图片数据写入到创建的资产中。
  4. 媒体扫描:为了让系统识别并添加到图库,需要通知媒体扫描器去扫描新添加的图片。这通常可以通过调用MediaStore相关的API或使用系统的MediaScannerConnection来完成。

如果在执行上述步骤时遇到问题,可以查阅HarmonyOS的官方文档或开发者社区以获取更多帮助。

HarmonyOS 鸿蒙Next学习https://www.itying.com/category-93-b0.html

回到顶部