HarmonyOS 怎么通过返回的Image路径,拿到具体的Image数据?

返回的照片path是:file://com.huawei.hmsapp.hiai/data/storage/el2/base/haps/doc/files/xxx/DocumentScanner\_20240819\_227146.jpeg

想通过这个path拿到具体的image数据。

阅读 550
1 个回答

可参考如下代码获取PixelMap数据,通过沙箱地址创建iamgeSource进而获取沙箱图片的PixelMap:

import { BusinessError, request } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';
import fileUri from '@ohos.file.fileuri';
import { image } from '@kit.ImageKit';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State param: image.PixelMap | undefined = undefined
  //阿祖图片的链接
  @State downloadUrl: string = 'xxx';
  @State filePath: string = ''

  build() {
    Column() {
      Button('click').onClick(async () => {
        //设置沙箱路径
        let filePath = getContext().cacheDir + '/Daniel' + Date.now() + '.jpg'
        //创建下载任务
        const task = await request.downloadFile(getContext(), {
          //设置图片的源地址
          url: this.downloadUrl,
          //设置图片存储路径
          filePath: filePath
        })
        //监听下载任务
        task.on('complete', () => {
          //保存图片的沙箱路径
          this.filePath = filePath
          console.log(`转换后的路径为:${fileUri.getUriFromPath(filePath)}`)
          //获取图片的沙箱路径
          this.filePath = fileUri.getUriFromPath(filePath)
          console.log(`filePath:${this.filePath}`)
          //创建iamgeSource示例
          const imageSource: image.ImageSource = image.createImageSource(filePath);
          // const imageSource: image.ImageSource = image.createImageSource(this.filePath);
          console.log(`ImageSource: ${JSON.stringify(imageSource.getImageInfoSync())}`);
          let decodingOptions: image.DecodingOptions = {
            sampleSize: 1,
            editable: true,
            desiredPixelFormat: 3,
            desiredSize: { width: 720, height: 720 }
          }
          // 创建pixelMap
          imageSource.createPixelMap(decodingOptions).then((pixelMap: image.PixelMap) => {
            this.param = pixelMap
            console.log("Succeeded in creating PixelMap")
          }).catch((err: BusinessError) => {
            console.error("Failed to create PixelMap")
          });
          AlertDialog.show(
            {
              message: '下载成功'
            }
          )
        })
      })
      if (this.param) {
        Image(this.param)
          .width(400)
          .aspectRatio(1)
      }
    }.width('100%').height('100%').justifyContent(FlexAlign.Center)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进