HarmonyOS鸿蒙Next中Image如何加载file://的本地图片文件

HarmonyOS鸿蒙Next中Image如何加载file://的本地图片文件 Image如何加载file://的本地图片文件

3 回复

如果你是想加载沙箱路径的图片,可以如下示例代码:

import common from '@ohos.app.ability.common';

@Entry
@Component
struct ImagePickerPage {
  @State uriStr: string = 'Hello World';

  build() {
    Row() {
      Column({space:5}) {
        Text(this.uriStr)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)

        Button("camera Image").onClick(() => {
          const context = getContext(this) as common.UIAbilityContext
          console.log('sss')
          context.startAbilityForResult({
            action: "ohos.want.action.imageCapture",
            parameters: {
              callBundleName: "com.example.ir_image", //返回的包名
              "supportMultiMode": true
            }
          }, (err, data) => {
            console.info("context:" + JSON.stringify(context))
            console.info("imageCapture:" + JSON.stringify(data))
            let uri: string = (data?.want?.parameters as Record<string, Object)]['resourceUri']?.toString(); //获取相片uri数据
            console.info("uri:" + JSON.stringify(uri))
            this.uriStr = uri

          })
        })

        //Image组件加载file格式的图片
        Image(this.uriStr)

      }
      .width('100%')
    }
    .height('100%')
  }
}

更多关于HarmonyOS鸿蒙Next中Image如何加载file://的本地图片文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,加载file://的本地图片文件可以通过Image组件实现。具体步骤如下:

  1. 获取本地图片路径:首先,确保你已获取到本地图片的file://路径。例如,file:///data/user/0/com.example.app/files/image.png

  2. 使用Image组件:在UI中,使用Image组件并设置src属性为本地图片路径。例如:

    <Image
        src="file:///data/user/0/com.example.app/files/image.png"
        width="200vp"
        height="200vp"/>
    
  3. 权限处理:确保应用已获取读取本地文件的权限。在config.json中声明权限:

    {
      "module": {
        "reqPermissions": [
          {
            "name": "ohos.permission.READ_MEDIA"
          }
        ]
      }
    }
    
  4. 动态加载:如果需要动态加载图片,可以在JavaScript中通过Image组件的src属性进行设置:

    this.$element('imageId').src = 'file:///data/user/0/com.example.app/files/image.png';
    

通过以上步骤,可以在HarmonyOS鸿蒙Next中成功加载file://的本地图片文件。

在HarmonyOS鸿蒙Next中,使用Image组件加载本地图片文件时,可以通过file://协议指定本地路径。首先,确保图片文件已放置在应用的资源目录中。然后,使用Image组件的src属性,并传入file://开头的路径。例如:

Image($r('app.media.local_image'))  // 使用资源ID加载
// 或
Image('file:///data/storage/el1/base/haps/entry/files/local_image.png')  // 使用绝对路径

确保路径正确且应用有访问权限。

回到顶部