将base64字符串保存为图片的方法

将base64字符串保存为图片的方法


HarmonyOS
2024-07-30 11:05:01
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
躺平嗑产品懒猫

在数据处理过程中,为了将base64编码格式的字符串转换为可存储的文件内容,我们可以采用`buffer.from`方法,该方法允许我们创建新的Buffer对象。一旦获得了该Buffer对象,我们可以进一步利用`fileIo.writeSync`方法,确保以同步的方式将转换后的Buffer对象内容写入到指定的文件中。

import { buffer } from '@kit.ArkTS';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { fileUri } from "@kit.CoreFileKit";
import { hilog } from '@kit.PerformanceAnalysisKit';

let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;

// data为需要转换的base64字符串,返回沙箱路径uri
export async function writeFile(data: string): Promise<string> {
  let uri = ''
  try {
    let filePath = filesDir + "/1.png";
    uri = fileUri.getUriFromPath(filePath);
    let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
    console.info("file fd: " + file.fd);
    const reg = new RegExp("data:image/\\w+;base64,")
    const base64 = data.replace(reg, "");
    console.log("base64flag", base64)
    const dataBuffer = buffer.from(base64, 'base64')
    let writeLen = fileIo.writeSync(file.fd, dataBuffer.buffer);
    hilog.info(0xA0c0d0,'uri',uri)
    fileIo.closeSync(file);
  }
  catch (Error) {
    hilog.error(0xA0c0d0,'Error',Error.code)
  }
  return uri;
}
  • 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.
分享
微博
QQ
微信
回复
2024-07-30 17:05:37
相关问题
base64字符如何转为图片保存
3657浏览 • 1回复 待解决
HarmonyOS 图片转为base64字符
871浏览 • 1回复 待解决
如何PixelMap转图片base64字符
1549浏览 • 1回复 待解决
如何图片base64字符转PixelMap?
1613浏览 • 1回复 待解决
PixelMap类型怎么转换成Base64字符
1589浏览 • 1回复 待解决
HarmonyOS SM2加签返回Base64字符
961浏览 • 1回复 待解决
HarmonyOS 如何base64图片保存到相册
2447浏览 • 1回复 待解决