本文主要是介绍鸿蒙 如何将base64的图片保存到相册,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
把一个base64图片 保存到鸿蒙手机 相册中怎么实现呢?
下面有2中方法
方案一:可以通过安全控件「保存控件(SaveButton)」实现。该控件对应媒体库写入特权。应用集成保存控件后,用户点击该控件,应用会获取10秒内单次访问媒体库特权接口的授权。
参考代码:
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import fs from '@ohos.file.fs';
import { http } from '@kit.NetworkKit';
import { promptAction } from '@kit.ArkUI';/** * 参考资料: * https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/photoaccesshelper-resource-guidelines-0000001774280306-V5#ZH-CN_TOPIC_0000001881258417__使用安全控件创建媒体资源 */
@Entry
@Component
struct Index {@State message: string = 'Hello World'@State saveButtonOptions: SaveButtonOptions = {icon: SaveIconStyle.FULL_FILLED,text: SaveDescription.SAVE_IMAGE,buttonType: ButtonType.Capsule}// 设置安全控件按钮属性build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)SaveButton(this.saveButtonOptions)// 创建安全控件按钮.onClick(async (event, result: SaveButtonOnClickResult) => {if (result == SaveButtonOnClickResult.SUCCESS) {let context = getContext();//获取相册管理模块的实例,用于访问和修改相册中的媒体文件 let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); // onClick触发后10秒内通过createAsset接口创建图片文件,10秒后createAsset权限收回let uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');// 创建媒体文件console.info('createAsset successfully, uri: ' + uri);let file = fs.openSync(uri, fs.OpenMode.READ_WRITE || fs.OpenMode.CREATE);let totalSize = 0;let httpRequest = http.createHttp();httpRequest.on("dataReceive", (data: ArrayBuffer) => {let writeLen = fs.writeSync(file.fd, data);totalSize = totalSize + writeLen;});httpRequest.requestInStream('https://developer.huawei.com/allianceCmsResource/resource/HUAWEI_Developer_VUE/images/homeNew/next- pc.png',{ method: http.RequestMethod.GET, connectTimeout: 3000, }, httpCode => {console.info('requestInStream HTTP CODE is', httpCode)})httpRequest.on("dataEnd", () => {fs.close(file);promptAction.showDialog({ title: "下载图片结束,并保存至相册", message: `图片大小:${totalSize}字节` })})} else {console.error('SaveButtonOnClickResult create asset failed');}})}.width('100%')}.height('100%')}
}
方案二:通过申请ACL权限。需要在module.json5文件中配置ohos.permission.WRITE_IMAGEVIDEO权限。类似这样: { // 允许修改用户公共目录的图片或视频文件。 "name": "ohos.permission.WRITE_IMAGEVIDEO", "reason": "$string:internet_permission_reason", "usedScene": { "when": "always" } }
import { abilityAccessCtrl, common } from '@kit.AbilityKit';import { photoAccessHelper } from '@kit.MediaLibraryKit';import fs from '@ohos.file.fs';import { http } from '@kit.NetworkKit';import { promptAction } from '@kit.ArkUI';@Entry@Component struct Index {@State message: string = 'Hello World'private appContext: common.Context = getContext(this);private atManager = abilityAccessCtrl.createAtManager();build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Button("保存图片").margin({ top: 10 }).onClick(async (event: ClickEvent) => { //申请权限并保存图片到图库try { //申请相册管理模块权限'ohos.permission.WRITE_IMAGEVIDEO' this.atManager.requestPermissionsFromUser(this.appContext, [ 'ohos.permission.WRITE_IMAGEVIDEO' ]).then(async () => { //权限申请成功,保存到图库let context = getContext();//获取相册管理模块的实例,用于访问和修改相册中的媒体文件let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context); // onClick触发后10秒内通过createAsset接口创建图片文件,10秒后createAsset权限收回let uri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');// 创建媒体文件console.info('createAsset successfully, uri: ' + uri);let file = fs.openSync(uri, fs.OpenMode.READ_WRITE || fs.OpenMode.CREATE);let totalSize = 0;let httpRequest = http.createHttp();httpRequest.on("dataReceive", (data: ArrayBuffer) => {let writeLen = fs.writeSync(file.fd, data); totalSize = totalSize + writeLen; });httpRequest.requestInStream('https://developer.huawei.com/allianceCmsResource/resource/HUAWEI_Developer_VUE/images/homeNew/next- pc.png',{ method: http.RequestMethod.GET, connectTimeout: 3000, }, httpCode => {console.info('requestInStream HTTP CODE is', httpCode) })httpRequest.on("dataEnd", () => { fs.close(file);promptAction.showDialog({ title: "下载图片结束,并保存至相册", message: `图片大小:${totalSize}字节` }) }) }) } catch (err) { console.error(`requestPermissionsFromUser call Failed! error: ${err.code}`); } }) }.width('100%') }.height('100%') }
}
这篇关于鸿蒙 如何将base64的图片保存到相册的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!