鸿蒙开发5.0【Native保存图片到应用沙箱 】

本示例主要介绍Native如何将网络上的图片及Rawfile中的图片保存到应用沙箱中。

效果图预览

1

使用说明

  1. rawfile路径下存有一张图片sandBoxTest.jpg。
  2. 设备连接上网络。
  3. 点击"保存Rawfile图片",前端通过调用Native侧暴露的saveImageOfRawfileCallback接口将rawfile中的图片sandBoxTest.jpg保存到应用沙箱中并返回沙箱路径到前端进行显示;点击“保存网络图片”,前端通过调用Native侧暴露的saveImageOfInternetCallback接口将网络图片保存到应用沙箱中并返回沙箱路径到前端进行显示。

实现思路

Native 保存网络图片到沙箱的实现主要步骤如下:

1.参考libcurl编译,编译libcurl.so等相关库文件。当前编译后加载libcurl.so时,通过hilog日志发现依赖了libcurl.so libcurl.so.4 libnghttp2.so libnghttp2.so.14 libzstd.so几个so文件。其中libcurl.so为开源的跨平台网络协议库,支持七层网络模型中应用层的各种协议;libnghttp2.so是一个HTTP/2和SPDY协议的实现,用于客户端,服务器,代理,和服务器推送应用;libzstd.so是一个实现了Zstandard算法的压缩库,常用于数据库、文件系统及网络传输等

2.将开源库libcurl相关的so文件以及封装了libcurl下载功能的libcurlDownload.so放入模块下的libs相应目录。

3.在CMakeLists中导入相关库文件。

target_link_directories(nativesavepictosandbox PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs/${OHOS_ARCH}/)

target_link_libraries(nativesavepictosandbox PUBLIC libace_napi.z.so libcurlDownload.so libhilog_ndk.z.so librawfile.z.so)

4.在前端通过调用Native中的saveImageOfInternetCallback接口获取沙箱地址并将沙箱地址转换为url地址绑定到Image组件显示。传入的参数为网络图片地址、应用的文件路径、沙箱中的文件名。

5.在Native的saveImageOfInternetCallback接口中通过调用libcurlDownload.so的接口将网络图片写入沙箱。

// TODO:知识点:使用dlopen动态加载so库,返回so库的句柄

void *handler = dlopen(libCurlDownload, RTLD_LAZY);

if (handler == nullptr) {

    // 抛出加载库失败的错误

    dlerror();

    return;

}



// 声明函数指针类型

typedef std::string (*DownloadInternetFileFunc)(char *, char *);

DownloadInternetFileFunc downloadInternetWrapper =

    reinterpret_cast<DownloadInternetFileFunc>(dlsym(handler, "DownloadInternetFileWrapper"));

if (downloadInternetWrapper) {

    // TODO:知识点:调用so的downloadInternetWrapper函数保存网路图片到沙箱

    CallbackInternetContext *internetContext = (CallbackInternetContext *)data;

    if (internetContext == nullptr) {

        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "saveImageOfInternet internetContext is null");

        return;

    }

    // 图片沙箱完整路径

    std::string targetSandboxPath = internetContext->sandboxDir + internetContext->FileName;

    OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, TAG, "saveImageOfInternet 保存沙箱文件:%{public}s",

        targetSandboxPath.c_str());



    internetContext->result = downloadInternetWrapper((char *)internetContext->internetPicUrl.c_str(),

    (char *)targetSandboxPath.c_str());

    OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, TAG, "saveImageOfInternet download finish");

    dlclose(handler);

} else {

    OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "saveImageOfInternet download function is null");

    dlclose(handler);

}

Native 保存Rawfile 图片到沙箱的实现主要步骤如下:

1.在前端通过调用Native中的saveImageOfRawfileCallback接口获取沙箱地址并将沙箱地址转换为url地址绑定到Image组件显示。传入的参数为js的资源对象、rawfile中的图片名、应用的文件路径。

Button($r('app.string.tbn_RawFilePicture'))

    .onClick(() => {

        // TODO:知识点:通过Native暴露的接口saveImageOfRawfileCallback接口获取rawfile中图片保存在沙箱中的路径

        testNapi.saveImageOfRawfileCallback(this.resMgr, this.rawfilePicPath, this.fileDir, ((result: string) => {

            if (result === undefined || result === '') {

                AlertDialog.show({

                    message: $r('app.string.rawfile_write_fail'),

                    alignment: DialogAlignment.Center

                });

                this.rawfileSandBoxPath = '';

            } else {

                this.rawfileSandBoxPath = fileUri.getUriFromPath(result);

                logger.info('[pic2sandbox]', `saveImageOfRawfile sandboxPath is ` + result);

            }

        }))

    })

2.在Native的saveImageOfRawfileCallback接口中通过Rawfile的API接口以及文件流将图片资源写入沙箱。

// 打开Rawfile文件。

RawFile *rawFile = OH_ResourceManager_OpenRawFile(rawFileContext->resMgr,

    rawFileContext->rawFileName.c_str());

if (rawFile == nullptr) {

    OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "saveImageOfRawfile OpenRawFile fail!");

    // 释放资源

    OH_ResourceManager_ReleaseNativeResourceManager(rawFileContext->resMgr);

    return;

}

// 获取文件大小

long imageDataSize = OH_ResourceManager_GetRawFileSize(rawFile);

// 申请内存

std::unique_ptr<char[]> imageData = std::make_unique<char[]>(imageDataSize);

// TODO:知识点:通过Rawfile的API接口读取Rawfile文件

long rawFileOffset = OH_ResourceManager_ReadRawFile(rawFile, imageData.get(), imageDataSize);

// 保存目标网络图片的沙箱路径

std::string targetSandboxPath = rawFileContext->sandboxDir + rawFileContext->rawFileName;

// TODO:知识点:通过std::ofstream,将读取的数据写入沙箱文件

std::ofstream outputFile(targetSandboxPath, std::ios::binary);

if (!outputFile) {

    OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, TAG, "saveImageOfRawfile 创建沙箱目标文件失败");

    // 释放资源

    OH_ResourceManager_CloseRawFile(rawFile);

    OH_ResourceManager_ReleaseNativeResourceManager(rawFileContext->resMgr);

    return;

}

// 写文件

outputFile.write(imageData.get(), imageDataSize);

工程结构& 模块类型

nativesavepictosandbox                               // har类型

    |---src\main\ets\view\

|   |---NativePictureToSandboxView.ets               // 视图层-图片写入沙箱场景主页面

    |---src\main\cpp\

|   |---native_picture_to_sandbox.cpp                // native层-图片写入沙箱业务逻辑

    |---src\main\cpp\curl                                // libcurl三方库头文件

以上就是本篇文章所带来的鸿蒙开发中一小部分技术讲解;想要学习完整的鸿蒙全栈技术。可以在结尾找我可全部拿到!
下面是鸿蒙的完整学习路线,展示如下:
1

除此之外,根据这个学习鸿蒙全栈学习路线,也附带一整套完整的学习【文档+视频】,内容包含如下

内容包含了:(ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!

鸿蒙【北向应用开发+南向系统层开发】文档

鸿蒙【基础+实战项目】视频

鸿蒙面经

在这里插入图片描述

为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值