HarmonyOS Image加载base64失败?

我想请问下Image组件加载Base64的问题,我使用 Image('data:image/[png|jpeg|bmp|webp];base64,[base64 data])这种方式加载图片失败,提示我failed to create image loader,image source type not supported ,但是我将 base64 通过以下方法保存,却能在本地文件看到图片,不知道是否格式配置或者base64需要经过处理才能显示

export async function writeFile(data: string): Promise<string> {

  let uri = ''
  try {
    let filePath = filesDir + "/1.";
    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);
  }
阅读 528
1 个回答

[base64 data]是Base64字符串数据,首先先在在线网站上验证下base64有没有问题,注意字符串中不能加中括号"[]"

示例demo如下:

const base64String= `/xxxxxxxxxxxxxxxxxx`    //base64编码
@Preview
@Entry
@Component
struct UiImage {
  @State imagestr: string = ''
  base64Image() {
    let begin = 'data:image/png;base64,' //后面不要有中括号
    return begin + base64String
  }
  aboutToAppear(): void {
    this.imagestr = this.base64Image()
  }

  build() {
    Row() {
      Column() {
        Image(this.imagestr)
          .width(300)
          .height(100)
          .backgroundColor(Color.Green)
          .onError((msg)=>{
            console.log('-----',JSON.stringify(msg))
          })
      }.width('100%')
    }.height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进