问题描述:在使用 OpenHarmony 4.0Release 的组件截图模块时碰到问题,截取的组件保存到应用沙箱后,导出到电脑桌面上无法查看。
IDE:DevEco Studio 4.0 Release,Build 4.0.0.600
SDK: OpenHarmony API 10,4.0.10.15
开发板:DAYU 200,内存8G
涉及的模块:
- @ohos.arkui.componentSnapshot (组件截图),API 10+,仅支持真机
https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md/ - @ohos.multimedia.image (图片处理),API 6+
https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/reference/apis/js-apis-image.md/ - @ohos.file.fs (文件管理) ,API 9+
https://docs.openharmony.cn/pages/v4.0/zh-cn/application-dev/reference/apis/js-apis-file-fs.md/
实现代码:
async snapshotWithComponent(componentId: string, callback: Callback<string>) {
//pixelMap to buffer.
let pixMap = await componentSnapshot.get(componentId)
Logger.debug(TAG, 'image info: ' + JSON.stringify(await pixMap.getImageInfo()))
this.pixMap = pixMap
let pixelBytesNumber: number = pixMap.getPixelBytesNumber();
Logger.debug(TAG, 'image pixelMap bytes: ' + pixelBytesNumber)
let buffer: ArrayBuffer = new ArrayBuffer(pixelBytesNumber);
await pixMap.readPixelsToBuffer(buffer)
await pixMap.release()
//create file in sandbox
let fileDir = getGlobalObject('sanBoxFileDir') as string
let filePath = fileDir + '/' + componentId + Date.now() + '.jpg';
if (!fs.accessSync(filePath)) {
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
Logger.info(TAG, "file fd: " + file.fd);
let fd = file.fd
let writeLen = fs.writeSync(fd, buffer);
fs.closeSync(file)
Logger.info(TAG, "write data to file succeed and size is: " + writeLen);
callback(filePath)
}
}
调用:
Text('照片').fontSize(20)
.onClick(event => {
this.snapshotWithComponent('page_title', (displayName: string) => {
Logger.info(TAG, 'writeSync data to file succeeded, displayName:' + displayName);
})
})
.id('page_title')
真机Log:
[ImageFileList], image info: {"size":{"width":60,"height":35},"pixelFormat":3,"colorSpace":2,"alphaType":2,"density":0}
[ImageFileList], image pixelMap bytes: 8400
[ImageFileList], file fd: 54
[ImageFileList], write data to file succeed and size is: 8400
[ImageFileList], writeSync data to file succeeded, displayName:/data/storage/el2/base/files/page_title1704867902094.jpg
真机中的应用沙箱路径中也存在该文件:
用电脑上的图片查看软件打开无法显示:
疑问:
- 既然图片尺寸大小、颜色空间、像素格式都有,为什么像素密度为0?
- 是接口本身的问题,还是说不应该这样实现?
请懂的小伙伴帮忙解答谢谢~