如何解决在相册中读取视频文件宽度时的崩溃

发布: (2026年1月12日 GMT+8 10:41)
3 min read
原文: Dev.to

Source: Dev.to

问题描述

在发布图文笔记时,选择系统相册中的图片或视频后,会获取系统相册资源的文件路径。在发布过程中,接口需要读取该图片/视频资源的宽度和高度。

从相册中选择视频文件后调用

photoAccessHelper.PhotoAsset.get(photoAccessHelper.PhotoKeys.WIDTH)

会导致崩溃。

问题代码

async uriGetAssets() {
  try {
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context);
    let predicates = new dataSharePredicates.DataSharePredicates();
    // Configure query conditions, use PhotoViewPicker to select the URI of the image to be queried.
    predicates.equalTo('uri', this.uri);
    let fetchOption = {
      fetchColumns: [],
      predicates: predicates
    };
    let fetchResult = await phAccessHelper.getAssets(fetchOption);
    // Obtain the PhotoAsset object corresponding to the URI and read partial information of the file.
    const asset = await fetchResult.getFirstObject();
    console.info('asset displayName: ', asset.displayName);
    console.info('asset uri: ', asset.uri);
    console.info('asset photoType: ', asset.photoType);
    // The following code will throw an error when trying to get the width and height.
    console.info('asset width: ', asset.get(photoAccessHelper.PhotoKeys.WIDTH));
    console.info('asset height: ', asset.get(photoAccessHelper.PhotoKeys.HEIGHT));
  } catch (error) {
    console.error('uriGetAssets failed with err: ' + JSON.stringify(error));
  }
}

背景知识

  • photoAccessHelper.PhotoAsset.get 接口文档。
  • photoAccessHelper.FetchOptions 接口文档。

排查过程

错误码 14000014 对应的信息为 “Member is not a valid PhotoKey”,说明 WIDTHHEIGHT 不是 get 方法的有效键。

可能原因:

  1. 视频文件未能读取,导致宽高不存在。
  2. 获取宽高的方法不正确。

由于视频已经成功读取,排除了第一种可能。问题出在获取信息的方法上。

photoAccessHelper.PhotoAsset.get() 接口仅支持查询四个属性:urimedia_typesubtypedisplay_name。对于其他属性,需要在 fetchColumns 中指定对应的 PhotoKeys。例如,要获取 title 属性,需要将 fetchColumns 设置为 ['title']

分析结论

photoAccessHelper.PhotoAsset.get() 只能查询上述四个属性。若要获取宽度、高度等其他属性,必须在 FetchOptionsfetchColumns 中加入相应字段。

解决方案

在配置 FetchOptions 时,将所需的属性(widthheight,以及可选的 title)加入 fetchColumns

// Add the properties for width, height and title that need to be obtained in the fetchColumns of the configuration item.
let fetchOption = {
  fetchColumns: ['width', 'height'],
  predicates: predicates
};

完成上述修改后,asset 对象中将包含 widthheight 的值,读取时不会再导致崩溃。

验证结果

问题已解决并验证:视频文件的宽度和高度能够正确获取,且不再出现崩溃。

Back to Blog

相关文章

阅读更多 »

构建高性能的 React Native 应用

嗨,你好,已经是2026年,构建 React Native 应用已经变得前所未有的简单。多亏了开源的 React Native 社区和 Expo 生态系统,任何…

天才大师与他高效的笨蛋仆人

“为什么!为什么!呃!” 当我看到Sanni抓住一把自己的头发并用力拉扯时,我的嘴角上扬。我靠在椅子上,注视着她眼中凶狠的光芒……