HarmonyOS 拍照最佳实现方案里面解析的photoUri无法用于Image组件展示吗?

根据拍照最佳实践里面的photoUri打印出来为沙箱地址 //file://media/Photo/20/IMG\_1719535410\_015/1719535310081.jpg

将这个地址赋予Image组件无法显示

但是new picker.PhotoViewPicker(context).select选取的本地图片也是沙箱地址 //file://media/Photo/12/IMG\_1719215593\_009/IMG\_20240624\_155133\_1.jpg

将这个地址赋予Image组件可以显示

请问是拍照获取的照片沙箱地址还需要做什么处理吗

阅读 598
1 个回答

使用Image组件, 得到文件沙箱路径后, 调用@ohos.file.fileuri模块的fileuri.getUriFromPath(file.path)将沙箱路径转化为沙箱uri, 传入之后即可正常显示.

代码请参考下面

import fileUri from '@ohos.file.fileuri';
import common from '@ohos.app.ability.common';
import fs from '@ohos.file.fs';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State uri: string = ""
  @State path: string = ""
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let context = getContext(this) as common.UIAbilityContext
            let filePath = context.filesDir + "/test.png"
            console.log('filepath-----',filePath)
            this.path = filePath
            let arrayBuff = context.resourceManager.getRawFileContentSync("img.png").buffer
            let file = fs.openSync(filePath,fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
            fs.writeSync(file.fd,arrayBuff)
            this.uri = fileUri.getUriFromPath(filePath)
            console.log('filepath1-----',filePath)
          })
        Image(this.uri)
          .objectFit(ImageFit.Contain)
          .width(200)
          .height(200)
      }
      .width('100%')
    }
    .height('100%')
  }
}