OpenHarmony 如何获取图片文件并且在Image组件显示
  e3WZ7MNIzbKV 2023年11月02日 56 0

预览效果:

1、获取系统文件数据FileAsset

获取文件对象的方法如下,入参为abilityContext和文件类型,示例代码如下:

async getFileAssets(context, fileType:mediaLibrary.MediaType):Promise<mediaLibrary.FetchFileResult>{

  Logger.debug('begin getFileAssets, fileType:'+fileType)

  let fileKeyObj=mediaLibrary.FileKey

  let imagesFetchOption={

    selections:fileKeyObj.MEDIA_TYPE+'= ?',

    selectionArgs:[fileType.toString()],

  }

  let fetchFileResult:mediaLibrary.FetchFileResult=undefined

  try{

    fetchFileResult=await this.getMediaLibrary(context).getFileAssets(imagesFetchOption)

    Logger.debug('fetchFileResult count:'+fetchFileResult.getCount())

  } catch(error) {

    Logger.error('fetchFileResult Error: '+JSON.stringify(error))

  }

  return fetchFileResult

}

2、通过获取的FileAsset对象,进行数据读取,并且转换为PixlMap对象:

async getPixelMapByFileAsset(fileAsset:mediaLibrary.FileAsset):Promise{

  if(fileAsset==undefined){

    Logger.error('fileAsset undefined')

    // 异常情况下统一返回undefined,不建议使用null

    return undefined

  }

  Logger.debug('begin getPixelMapByFileAsset:'+fileAsset.displayName)

  let fd:number=undefined

  let pixelMap=undefined

  try{

    fd=await fileAsset.open('rw')

    Logger.debug('getPixelMapByFileAsset fd: '+fd)

    let imageSource=image.createImageSource(fd)

    Logger.debug('imageSource: '+JSON.stringify(imageSource))

    let decodingOptions={

      sampleSize:1,

      editable:true,

      desiredSize:{width:3000,height:4000},

      rotate:0,

      desiredPixelFormat:3,

      desiredRegion:{size:{height:6000,width:8000},x:0,y:0},

      index:0

    }

    pixelMap= await imageSource.createPixelMap(decodingOptions)

    Logger.debug('pixel size: '+pixelMap.getPixelBytesNumber())

    fileAsset.close(fd)

  }catch(err){

    Logger.debug('err: '+JSON.stringify(err))

  }

  return pixelMap

}

3、获取到pixelMap,可以直接传到Image组件中,显示出来


大家可以参考具体的示例代码,有更多功能待大家解锁,源码链接:文件管理

另外推荐OpenHarmony官方的sample仓,里面有大量示例代码,可以端到端指导各个场景示例代码,链接:OpenHarmony/applications_app_samples - 码云 - 开源中国 (gitee.com)

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
e3WZ7MNIzbKV