如何解决在相册中读取视频文件宽度时的崩溃
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”,说明 WIDTH 与 HEIGHT 不是 get 方法的有效键。
可能原因:
- 视频文件未能读取,导致宽高不存在。
- 获取宽高的方法不正确。
由于视频已经成功读取,排除了第一种可能。问题出在获取信息的方法上。
photoAccessHelper.PhotoAsset.get() 接口仅支持查询四个属性:uri、media_type、subtype 和 display_name。对于其他属性,需要在 fetchColumns 中指定对应的 PhotoKeys。例如,要获取 title 属性,需要将 fetchColumns 设置为 ['title']。
分析结论
photoAccessHelper.PhotoAsset.get() 只能查询上述四个属性。若要获取宽度、高度等其他属性,必须在 FetchOptions 的 fetchColumns 中加入相应字段。
解决方案
在配置 FetchOptions 时,将所需的属性(width、height,以及可选的 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 对象中将包含 width 与 height 的值,读取时不会再导致崩溃。
验证结果
问题已解决并验证:视频文件的宽度和高度能够正确获取,且不再出现崩溃。