HarmonyOS 如何将base64的图片保存到相册

现在有一个字符串格式的base64图片,如下:

let base64="data:image/png;base64,iVBORxxxxxxRMax/uBxxx
  • 1.

想将这个base64图片保存到相册中,应该如何实现?

HarmonyOS
2024-09-02 09:47:17
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
put_get

先把base64转成文件流,然后使用@ohos.file.fs的fs.write方法先把图片写到自己的项目目录里面,然后在使用@ohos.file.picker读取目录里面的图片,保存到用户手机上。

参考示例如下:

saveImage() { 
  //文件保存路径 
  let uri = ''; 
  try { let PhotoSaveOptions = new picker.PhotoSaveOptions(); 
    //保存图片默认名称  
    PhotoSaveOptions.newFileNames = ['test.png']; 
    let photoPicker = new picker.PhotoViewPicker(); 
    //调起系统的图片保存功能  
    photoPicker.save(PhotoSaveOptions).then((PhotoSaveResult) => { 
      uri = PhotoSaveResult[0]; 
      //获取图片的base64字符串  
      let imageStr = '图片的base64字符串'.split(','); 
      //打开文件 
      let file = fs.openSync(uri, fs.OpenMode.READ_WRITE); 
      //base64字符串转成 
      buffer const decodeBuffer = buffer.from(imageStr, 'base64').buffer; 
      //写入文件  
      fs.writeSync(file.fd, decodeBuffer); 
      //关闭文件 
      fs.closeSync(file); }).catch((err: Error) => { console.error(err + ''); }) 
  } 
  catch (e) { console.error(e); } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

图片保存到相册,可以通过2种方式实现。

方案一:可以通过安全控件「保存控件(SaveButton)」实现。该控件对应媒体库写入特权。应用集成保存控件后,用户点击该控件,应用会获取10秒内单次访问媒体库特权接口的授权。

方案一参考代码:

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'  
@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%') 
 }  
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.

参考资料:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/photoaccesshelper-resource-guidelines-0000001774280306-V5#ZH-CN_TOPIC_0000001881258417__使用安全控件创建媒体资源

方案二:通过申请ACL权限。

需要在module.json5文件中配置ohos.permission.WRITE_IMAGEVIDEO权限。类似这样:

{ // 允许修改用户公共目录的图片或视频文件。 "name": "ohos.permission.WRITE_IMAGEVIDEO", "reason": "$string:internet_permission_reason", "usedScene": { "when": "always" } },
  • 1.

方案二参考代码:

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%')  
}  
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
分享
微博
QQ
微信
回复
2024-09-02 16:18:30


相关问题
HarmonyOS 如何base64图片保存到相册
1356浏览 • 1回复 待解决
HarmonyOS如何将图片Base64
1957浏览 • 1回复 待解决
HarmonyOS 如何将图片保存到相册
763浏览 • 1回复 待解决
HarmonyOS 如何将图片压缩并转成base64
1249浏览 • 1回复 待解决
HarmonyOS 如何将base64数据转换为图片
1431浏览 • 1回复 待解决
HarmonyOS 如何将沙盒图片转位base64
988浏览 • 1回复 待解决
HarmonyOS如何将PixelMap保存到相册
1519浏览 • 1回复 待解决
有谁知道如何将图片保存到相册
2424浏览 • 1回复 待解决
HarmonyOS 如何将文件流转为base64
1146浏览 • 1回复 待解决
如何将PixelMap转图片base64字符串?
1546浏览 • 1回复 待解决
如何将图片base64字符串转PixelMap?
1601浏览 • 1回复 待解决
如何将视频保存到相册以及主机端
6630浏览 • 1回复 待解决
base64字符串保存图片方法
2056浏览 • 1回复 待解决
HarmonyOS 图片Base64编码
839浏览 • 1回复 待解决