鸿蒙HarmonyOS应用开发之Rawfile开发指导_rawfiledescriptor 怎么导入(4)

  1. 根据RawDir实例,使用OH_ResourceManager_GetRawFileCount接口获取对应目录下的rawfile文件总数 。

int count = OH_ResourceManager_GetRawFileCount(rawDir);

  1. 根据RawDir实例,使用OH_ResourceManager_GetRawFileName接口获取目录下对应index的rawfile文件名。

for (int index = 0; index < count; index++) {
std::string fileName = OH_ResourceManager_GetRawFileName(rawDir, index);
}

  1. 根据NativeResourceManager实例,使用OH_ResourceManager_OpenRawFile接口获取指定文件名的RawFile实例

RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str());

  1. 根据RawFile实例,使用OH_ResourceManager_GetRawFileSize接口获取对应rawfile文件大小。

long rawFileSize = OH_ResourceManager_GetRawFileSize(rawFile);

  1. 根据RawFile实例,使用OH_ResourceManager_SeekRawFile接口指定rawfile偏移量。

int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0);
int position = OH_ResourceManager_SeekRawFile(rawFile, 0 , 1);
int position = OH_ResourceManager_SeekRawFile(rawFile, -10, 2);

  1. 根据RawFile实例,使用OH_ResourceManager_GetRawFileOffset接口获取rawfile偏移量。

long rawFileOffset = OH_ResourceManager_GetRawFileOffset(rawFile)

  1. 根据RawFile实例,使用OH_ResourceManager_ReadRawFile接口读取rawfile文件内容。

std::unique_ptr<char[]> mediaData = std::make_unique<char[]>(rawFileSize);
long rawFileOffset = OH_ResourceManager_ReadRawFile(rawFile, mediaData.get(), rawFileSize);

  1. 根据RawFile实例,使用OH_ResourceManager_GetRawFileRemainingLength接口读取rawfile文件的剩余长度。

int64_t rawFileRemainingSize = OH_ResourceManager_GetRawFileRemainingLength(rawFile);

  1. 根据RawFile实例,使用OH_ResourceManager_CloseRawFile接口释放rawfile文件相关资源。

OH_ResourceManager_CloseRawFile(rawFile);

  1. 根据RawDir实例,使用OH_ResourceManager_CloseRawDir接口释放rawfile目录相关资源。

OH_ResourceManager_CloseRawDir(rawDir);

  1. 根据RawFile实例,使用OH_ResourceManager_GetRawFileDescriptor接口获取rawfile的RawFileDescriptor。

RawFileDescriptor descriptor;
bool result = OH_ResourceManager_GetRawFileDescriptor(rawFile, descriptor);

  1. 根据RawFileDescriptor实例,使用OH_ResourceManager_ReleaseRawFileDescriptor接口关闭rawfile的fd。

OH_ResourceManager_ReleaseRawFileDescriptor(descriptor);

  1. 根据NativeResourceManager实例,使用OH_ResourceManager_ReleaseNativeResourceManager接口释放native resource manager。

OH_ResourceManager_ReleaseNativeResourceManager(nativeResourceManager);

开发步骤

以ArkTS侧获取rawfile文件列表、rawfile文件内容、rawfile描述符{fd, offset, length}三种调用方式为例。

1. 创建工程

2. 添加依赖

创建完成后,IDE会在工程生成cpp目录,目录有libentry/index.d.ts、hello.cpp、CMakeLists.txt等文件。

  1. 打开src/main/cpp/CMakeLists.txt,在target_link_libraries依赖中添加资源的librawfile.z.so以及日志依赖libhilog_ndk.z.so。

target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so librawfile.z.so)

  1. 打开src/main/cpp/types/libentry/index.d.ts文件,此文件声明了应用侧函数getFileList、getRawFileContent、getRawFileDescriptor。

import resourceManager from ‘@ohos.resourceManager’;
export const getFileList: (resmgr: resourceManager.ResourceManager, path: string) => Array;
export const getRawFileContent: (resmgr: resourceManager.ResourceManager, path: string) => Uint8Array;
export const getRawFileDescriptor: (resmgr: resourceManager.ResourceManager, path: string) => resourceManager.RawFileDescriptor;

3. 修改源文件

  1. 打开src/main/cpp/hello.cpp文件,文件Init会对当前方法进行初始化映射,这里定义对外接口为getFileList、getRawFileContent、getRawFileDescriptor,映射C++接口分别为GetFileList、GetRawFileContent、GetRawFileDescriptor。

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
napi_property_descriptor desc[] = {
{ “getFileList”, nullptr, GetFileList, nullptr, nullptr, nullptr, napi_default, nullptr },
{ “getRawFileContent”, nullptr, GetRawFileContent, nullptr, nullptr, nullptr, napi_default, nullptr },
{ “getRawFileDescriptor”, nullptr, GetRawFileDescriptor, nullptr, nullptr, nullptr, napi_default, nullptr }
};

napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
return exports;
}
EXTERN_C_END

  1. 把src/main/cpp/hello.cpp文件中,增加对应的三个方法,如下所示

static napi_value GetFileList(napi_env env, napi_callback_info info)
static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
static napi_value GetRawFileDescriptor(napi_env env, napi_callback_info info)

  1. 在hello.cpp文件中获取Js的资源对象,并转为Native的资源对象,即可调用资源的Native接口,获取rawfile列表、rawfile文件内容以及rawfile描述符{fd, offset, length}三种调用方式示例代码如下:

#include <rawfile/raw_file.h>
#include <rawfile/raw_dir.h>
#include <rawfile/raw_file_manager.h>

// 示例一:获取rawfile文件列表 GetFileList
static napi_value GetFileList(napi_env env, napi_callback_info info)
{
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, “NDKTest Begin”);
size_t requireArgc = 3;
size_t argc = 2;
napi_value argv[2] = { nullptr };
// 获取参数信息
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);

// argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。
NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);

// 获取函数argv[1],此为为rawfile相对路径
size_t strSize;
char strBuf[256];
napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
std::string dirName(strBuf, strSize);

// 获取对应的rawDir指针对象
RawDir* rawDir = OH_ResourceManager_OpenRawDir(mNativeResMgr, dirName.c_str());

// 获取rawDir下文件及文件夹数量
int count = OH_ResourceManager_GetRawFileCount(rawDir);

// 遍历获取文件名称,并保存
std::vectorstd::string tempArray;
for(int i = 0; i < count; i++) {
std::string filename = OH_ResourceManager_GetRawFileName(rawDir, i);
tempArray.emplace_back(filename);
}

napi_value fileList;
napi_create_array(env, &fileList);
for (size_t i = 0; i < tempArray.size(); i++) {
napi_value jsString;
napi_create_string_utf8(env, tempArray[i].c_str(), NAPI_AUTO_LENGTH, &jsString);
napi_set_element(env, fileList, i, jsString);
}

// 关闭打开的指针对象
OH_ResourceManager_CloseRawDir(rawDir);
OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
return fileList;
}

// 示例二:获取rawfile文件内容 GetRawFileContent
napi_value CreateJsArrayValue(napi_env env, std::unique_ptr<uint8_t[]> &data, long length)
{
napi_value buffer;
napi_status status = napi_create_external_arraybuffer(env, data.get(), length,
[](napi_env env, void *data, void hint) {
delete[] static_cast<char
>(data);
}, nullptr, &buffer);
if (status != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, “Failed to create external array buffer”);
return nullptr;
}
napi_value result = nullptr;
status = napi_create_typedarray(env, napi_uint8_array, length, buffer, 0, &result);
if (status != napi_ok) {
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, “Failed to create media typed array”);
return nullptr;
}
data.release();
return result;
}
static napi_value GetRawFileContent(napi_env env, napi_callback_info info)
{
OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, tag, “GetFileContent Begin”);
size_t requireArgc = 3;
size_t argc = 2;
napi_value argv[2] = { nullptr };
// 获取参数信息
napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);

// argv[0]即为函数第一个参数Js资源对象,OH_ResourceManager_InitNativeResourceManager转为Native对象。
NativeResourceManager *mNativeResMgr = OH_ResourceManager_InitNativeResourceManager(env, argv[0]);
size_t strSize;
char strBuf[256];
napi_get_value_string_utf8(env, argv[1], strBuf, sizeof(strBuf), &strSize);
std::string filename(strBuf, strSize);

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数HarmonyOS鸿蒙开发工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年HarmonyOS鸿蒙开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上HarmonyOS鸿蒙开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新

如果你觉得这些内容对你有帮助,可以添加VX:vip204888 (备注鸿蒙获取)
img

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

,基本涵盖了95%以上HarmonyOS鸿蒙开发知识点,真正体系化!**

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新

如果你觉得这些内容对你有帮助,可以添加VX:vip204888 (备注鸿蒙获取)
[外链图片转存中…(img-fjQdiez0-1712812085342)]

一个人可以走的很快,但一群人才能走的更远。不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎扫码加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

<think>我们正在讨论HarmonyOS NEXT中显示JPG图片的问题。根据用户的问题,他想要在鸿蒙开发中显示JPG图片数据。我们可以参考提供的引用资料,特别是引用[4]中的代码示例,该示例展示了如何从资源中获取JPG图片并显示。 在HarmonyOS NEXT中,显示图片通常使用`<Image>`组件。同时,我们需要通过资源管理获取图片数据,然后创建ImageSource,进而生成PixelMap,最后将PixelMap设置给Image组件。 根据引用[4]的示例,我们可以分解为以下步骤: 1. 获取资源管理器(resourceManager)并读取图片文件(如test.jpg)的原始数据。 2. 将原始数据转换为ArrayBuffer,然后创建ImageSource。 3. 通过ImageSource创建PixelMap(位图数据)。 4. 将PixelMap设置给Image组件进行显示。 但是,需要注意的是,引用[4]中的代码仅展示了如何从资源文件中获取图片并创建PixelMap,并没有直接展示如何显示在Image组件上。因此,我们需要结合ArkUI的Image组件来显示。 在ArkUI中,Image组件可以通过设置`src`属性来显示图片,而`src`属性可以接受资源路径、PixelMap等。 因此,我们可以这样实现: 步骤1:将图片文件(如test.jpg)放在resources/base/media目录下(如果没有media目录,可以创建)。 步骤2:在UI中使用Image组件,并设置其src属性为资源路径($r('app.media.test'))即可直接显示。 但是,如果用户希望从二进制数据(比如通过网络下载的JPG数据)显示,那么就需要使用引用[4]中的方法,将二进制数据转换为PixelMap,然后设置给Image组件。 因此,我们分两种情况: 情况一:图片是本地资源文件(放在resources目录下) 情况二:图片是二进制数据(比如从网络下载或内存中) 用户的问题中提到了“显示JPG图片数据”,这里的数据可能是二进制数据,所以我们重点放在情况二。 以下是如何在ArkUI(使用TypeScript)中显示二进制JPG图片数据的步骤: 1. 获取二进制数据(Uint8Array格式)。 2. 使用`image.createImageSource`创建ImageSource。 3. 通过ImageSource创建PixelMap。 4. 将PixelMap设置给Image组件的src属性。 示例代码(基于ArkTS): 假设我们有一个包含JPG图片二进制数据的Uint8Array(例如从网络下载或读取文件得到),我们可以这样显示: ```typescript import image from '@ohos.multimedia.image'; import resourceManager from '@ohos.resourceManager'; @Entry @Component struct ImageDisplayExample { // 用于存储PixelMap @State pixelMap: image.PixelMap | undefined = undefined; aboutToAppear() { // 假设我们有一个Uint8Array类型的jpg数据,这里用空数组代替,实际应从网络或文件读取 // 这里我们模拟一个从资源文件读取的过程,实际中可能从网络获取 const context = getContext(this); resourceManager.getResourceManager().then(resMgr => { resMgr.getRawFileContent('test.jpg').then(fileData => { console.log("Succeeded in getting RawFileContent"); // 获取ArrayBuffer const buffer = fileData.buffer.slice(0); // 创建ImageSource const imageSource = image.createImageSource(buffer); // 创建PixelMap imageSource.createPixelMap().then(pixelMap => { this.pixelMap = pixelMap; }).catch(err => { console.error("Failed to create PixelMap: " + JSON.stringify(err)); }); }).catch(err => { console.error("Failed to get RawFileContent: " + JSON.stringify(err)); }); }).catch(err => { console.error("Failed to get resourceManager: " + JSON.stringify(err)); }); } build() { Column() { // 使用Image组件显示 if (this.pixelMap) { Image(this.pixelMap) .width(200) .height(200) } else { Text('Loading...') } } .width('100%') .height('100%') } } ``` 注意:上述代码中,我们使用了`resourceManager`来读取resources/rawfile目录下的test.jpg文件(注意:getRawFileContent读取的是rawfile目录下的文件,所以需要将test.jpg放在resources/rawfile目录下)。如果我们的二进制数据来自其他途径(如网络),则不需要使用resourceManager,直接使用获取到的Uint8Array即可。 例如,如果我们从网络获取到二进制数据(ArrayBuffer),可以这样: ```typescript // 假设response是网络请求返回的ArrayBuffer const buffer = response; // response是ArrayBuffer类型 const imageSource = image.createImageSource(buffer); imageSource.createPixelMap().then(pixelMap => { this.pixelMap = pixelMap; }); ``` 另外,需要注意的是,HarmonyOS NEXT的Image组件可以直接显示网络图片,通过设置src为网络URL,但这里用户要求显示JPG图片数据(二进制数据),所以我们需要转换为PixelMap。 总结: 在HarmonyOS NEXT中显示JPG图片数据(二进制数据)的关键步骤是: 1. 将二进制数据(Uint8Array或ArrayBuffer)转换为ImageSource。 2. 通过ImageSource创建PixelMap。 3. 将PixelMap设置为Image组件的src。 这样,就可以在应用界面上显示JPG图片了。 参考文献: [^4] 提供了创建ImageSource和PixelMap的代码示例。 根据用户的问题,我们提供了上述解决方案。如果用户有其他疑问,可以进一步探讨。 相关问题: 1.HarmonyOS NEXT中如何显示网络图片(直接通过URL)? 2. 如何处理图片加载失败的情况? 3. 如何对图片进行缩放、裁剪等操作?</think>在 HarmonyOS NEXT 中显示 JPG 图片数据主要通过 `Image` 组件和图像处理 API 实现,以下是详细步骤和代码示例: ### 核心步骤 1. **获取图片数据** 从资源文件、网络或内存中获取 JPG 二进制数据(`Uint8Array` 格式) 2. **创建 ImageSource 对象** 使用 `@ohos.multimedia.image` 模块将二进制数据转换为图像源: ```typescript import image from '@ohos.multimedia.image'; // 假设 jpgData 是 Uint8Array 类型的 JPG 数据 const imageSource = image.createImageSource(jpgData.buffer); ``` 3. **生成 PixelMap 位图** 从 ImageSource 解码生成可显示的位图对象: ```typescript imageSource.createPixelMap().then((pixelMap: image.PixelMap) => { // 此处获取到可渲染的位图 }).catch((error: BusinessError) => { console.error("解码失败: " + error.message); }); ``` 4. **通过 Image 组件显示** 在 ArkUI 中将 PixelMap 绑定到 Image 组件: ```typescript @State pixelMap: image.PixelMap | null = null; build() { Column() { if (this.pixelMap) { Image(this.pixelMap) // 直接使用 PixelMap .width(200) .height(200) .objectFit(ImageFit.Contain) } else { Text('图片加载中...') } } } ``` ### 完整示例代码 ```typescript import image from '@ohos.multimedia.image'; import { BusinessError } from '@ohos.base'; @Entry @Component struct ImageDisplayExample { @State pixelMap: image.PixelMap | null = null; aboutToAppear() { // 1. 获取JPG数据(示例从资源读取) const context: Context = getContext(this); context.resourceManager.getRawFileContent('test.jpg') .then((fileData: Uint8Array) => { console.log("获取JPG数据成功"); // 2. 创建ImageSource const buffer = fileData.buffer.slice(0); const imageSource: image.ImageSource = image.createImageSource(buffer); // 3. 生成PixelMap imageSource.createPixelMap() .then((pixelMap: image.PixelMap) => { this.pixelMap = pixelMap; }) }).catch((error: BusinessError) => { console.error("处理失败: " + error.message); }); } build() { Column() { if (this.pixelMap) { // 4. 显示图片 Image(this.pixelMap) .width('90%') .height(300) .borderRadius(10) .overlay('JPG图片', { align: Alignment.Bottom, offset: { y: 10 } }) } else { ProgressBar() .width(100) .height(100) .color(Color.Blue) Text('解码图片中...').margin(10) } } .width('100%') .height('100%') .padding(20) } } ``` ### 关键注意事项 1. **资源放置** JPG 文件需放在项目的 `resources/rawfile` 目录下(如 `test.jpg`) 2. **权限声明** 如果加载网络图片,需在 `module.json5` 中添加网络权限: ```json "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ] ``` 3. **内存管理** 使用后释放资源避免内存泄漏: ```typescript // 组件销毁时 aboutToDisappear() { if (this.pixelMap) { this.pixelMap.release(); } } ``` 4. **性能优化** 大图片建议先获取尺寸再按需解码: ```typescript imageSource.getImageInfo().then((info: image.ImageInfo) => { console.log(`图片尺寸: ${info.size.width}x${info.size.height}`); }); ``` ### 替代方案(直接显示资源文件) 如果只需显示本地资源文件,可直接使用资源路径: ```typescript Image($r('app.media.test_jpg')) // 放在resources/base/media目录 .width(200) .height(200) ``` > 提示:鸿蒙的 `Image` 组件原生支持 JPG/PNG/WEBP 等常见格式[^4],解码过程会自动处理色彩空间转换和 EXIF 方向信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值