新版DevEco及模拟器相机功能无法使用,沙盒里没有图片,在模拟及调试图片选择及相关功能时没有素材,在没有鸿蒙真机的情况下,可以使用以下方法解决:
使用保存控件,将media资源下的图片保存到相册,即可在程序中选择和使用。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
//存储到相册照片用于模拟器调试 async savePhotoToGallery(context: common.UIAbilityContext) { let helper = photoAccessHelper.getPhotoAccessHelper(context); try { // onClick触发后10秒内通过createAsset接口创建图片文件,10秒后createAsset权限收回。 let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg'); // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制。 let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件。 context.resourceManager.getMediaContent($r('app.media.lotus').id, 0) //注意,此处资源名称按需修改 .then(async value => { let media = value.buffer; // 写到媒体库文件中。 await fileIo.write(file.fd, media); await fileIo.close(file.fd); promptAction.showToast({ message: '已保存至相册!' }); }); } catch (error) { const err: BusinessError = error as BusinessError; console.error(`Failed to save photo. Code is ${err.code}, message is ${err.message}`); } } //在build合适的地方增加下载按钮 SaveButton() .padding({top: 12, left: 24, right: 24}) .onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => { if (result === SaveButtonOnClickResult.SUCCESS) { const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext; // 免去权限申请和权限请求等环节,获得临时授权,保存对应图片。 this.savePhotoToGallery(context); } else { promptAction.showToast({ message: '设置权限失败!' }) } }) |