#鸿蒙通关秘籍#利用Native如何将Rawfile中的图片保存到应用沙箱?

HarmonyOS
2024-12-06 15:57:21
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
SCIM梦幻旅

将Rawfile中的图片保存到沙箱的步骤如下:

  1. 在前端,需要通过调用Native的saveImageOfRawfile接口,获取沙箱的路径,并将这个路径转换为URI绑定到Image组件上:

    Button($r('app.string.tbn_RawFilePicture'))
      .onClick(() => {
        let sandBoxPath = testNapi.saveImageOfRawfile(this.resMgr, this.rawfilePicPath, this.fileDir);
        if (sandBoxPath === undefined) {
          AlertDialog.show({ message: `Rawfile图片写入失败`, alignment: DialogAlignment.Center });
          this.rawfileSandBoxPath = '';
        } else {
          this.rawfileSandBoxPath = fileUri.getUriFromPath(sandBoxPath);
        }
      })
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
  2. 在Native层,使用Rawfile API读取图片资源并写入沙箱:

    RawFile *rawFile = OH_ResourceManager_OpenRawFile(mNativeResMgr, rawFileName.c_str());
    if (rawFile == nullptr) {
        OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
        return nullptr;
    }
    
    long imageDataSize = OH_ResourceManager_GetRawFileSize(rawFile);
    std::unique_ptr<char[]> imageData = std::make_unique<char[]>(imageDataSize);
    long rawFileOffset = OH_ResourceManager_ReadRawFile(rawFile, imageData.get(), imageDataSize);
    
    std::string targetSandboxPath = targetDirectory + rawFileName;
    std::ofstream outputFile(targetSandboxPath, std::ios::binary);
    if (!outputFile) {
        OH_ResourceManager_CloseRawFile(rawFile);
        OH_ResourceManager_ReleaseNativeResourceManager(mNativeResMgr);
        return nullptr;
    }
    
    outputFile.write(imageData.get(), imageDataSize);
    
    • 1.
    • 2.
    • 3.
    • 4.
    • 5.
    • 6.
    • 7.
    • 8.
    • 9.
    • 10.
    • 11.
    • 12.
    • 13.
    • 14.
    • 15.
    • 16.
    • 17.
    • 18.
    • 19.

按照上述步骤进行操作,可以实现将Rawfile中的图片保存到应用沙箱。通过方法调用与必要的资源管理,可确保图片资源在特定的沙箱路径中被正确保存和使用。

分享
微博
QQ
微信
回复
2024-12-06 17:50:18


相关问题
HarmonyOS 如何将图片保存到相册
439浏览 • 1回复 待解决
如何将像素点保存到图片文件
2788浏览 • 1回复 待解决
有谁知道如何将图片保存到相册
2078浏览 • 1回复 待解决
HarmonyOS 如何将base64图片保存到相册
1963浏览 • 1回复 待解决
应用沙箱图片保存到图库
1921浏览 • 1回复 待解决
HarmonyOS如何将PixelMap保存到相册?
1161浏览 • 1回复 待解决
如何将Pixmap保存到本地文件?
902浏览 • 1回复 待解决
HarmonyOS 如何将PixelMap保存沙箱
589浏览 • 1回复 待解决
如何将视频保存到相册以及主机端
6292浏览 • 1回复 待解决
如何将一段文字保存到剪切板
966浏览 • 1回复 待解决