图片接收
====

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/2a/v3/RYEIW3huRFCbFgcUi8g6Ug/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073521Z&HW-CC-Expire=86400&HW-CC-Sign=C65F1856B53C94E4A71323D1AB7FE31AC7C02ECC7A5843E085946BF193B38472)

当前开发指导使用的接口为[Image](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/capi-image)模块下的C API，可完成图片编解码，图片接收器，处理图像数据等功能。这部分API在API version 11之前发布，在后续的版本不再增加新功能，**不再推荐使用**。

开发者可使用[Image\_NativeModule](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/capi-image-nativemodule)模块下的C API，不仅提供上述图片框架基础功能，还可以完成多图编解码等新特性，相关开发指导请参考[图片开发指导(C/C++)](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/image-source-c)节点下的内容。这部分API从API version 12开始支持，并将持续演进，**推荐开发者使用**。

两套C API不建议同时使用，在部分场景下存在不兼容的问题。

图片接收类，用于获取组件surface id，接收最新的图片和读取下一张图片，以及释放ImageReceiver实例。

#### 开发步骤

#### \[h2\]添加依赖

在进行应用开发之前，开发者需要打开native工程的src/main/cpp/CMakeLists.txt，在target\_link\_libraries依赖中添加libace\_napi.z.so、libimage\_ndk.z.so、libimage\_receiver\_ndk.z.so、libnative\_image.so以及日志依赖libhilog\_ndk.z.so。

target\_link\_libraries(entry PUBLIC libace\_napi.z.so libhilog\_ndk.z.so libimage\_ndk.z.so libimage\_receiver\_ndk.z.so libnative\_image.so)

#### \[h2\]添加接口映射

打开src/main/cpp/hello.cpp文件，在Init函数中添加接口映射如下：

EXTERN\_C\_START
static napi\_value Init(napi\_env env, napi\_value exports)
{
    napi\_property\_descriptor desc\[\] = {
        { "createFromReceiver", nullptr, createFromReceiver, nullptr, nullptr, nullptr, napi\_default, nullptr },
    };

    napi\_define\_properties(env, exports, sizeof(desc) / sizeof(desc\[0\]), desc);
    return exports;
}
EXTERN\_C\_END

#### \[h2\]添加权限申请

此处通过camera图片获取输入数据，需要申请权限ohos.permission.CAMERA，申请方式请参考[向用户申请授权](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/request-user-authorization)。

#### \[h2\]JS侧调用

1.  打开src\\main\\cpp\\types\\libentry\\index.d.ts（其中libentry根据工程名生成），导入如下引用文件：
    
    import { image } from '@kit.ImageKit';
    
    export const createFromReceiver: (a: image.ImageReceiver) => image.Image;
    
2.  打开src\\main\\ets\\pages\\index.ets，导入"libentry.so（根据工程名生成）"，调用Native接口，传入JS的资源对象。示例如下：
    
    import testNapi from 'libentry.so';
    import { image } from '@kit.ImageKit';
    import { common, abilityAccessCtrl } from '@kit.AbilityKit';
    import { camera } from '@kit.CameraKit';
    
    @Entry
    @Component
    struct Index {
      private receiver: image.ImageReceiver | undefined = undefined;
      func (){
         let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
         abilityAccessCtrl.createAtManager().requestPermissionsFromUser(context,\['ohos.permission.CAMERA'\]).then(async () => {
            let cameraManager = await camera.getCameraManager(context);
            // 获取支持的相机设备对象。
            let cameraDevices: Array<camera.CameraDevice> = cameraManager.getSupportedCameras();
            if (cameraDevices.length <= 0) {
            return;
            }
            // 获取对应相机设备的profiles。
            let profiles: camera.CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraDevices\[0\], camera.SceneMode.NORMAL\_PHOTO);
            let previewProfiles: Array<camera.Profile> = profiles.previewProfiles;
            if (previewProfiles.length <= 0) {
            return;
            }
            let profileObj = previewProfiles\[0\];
            this.receiver = image.createImageReceiver({width:profileObj.size.width, height:profileObj.size.height}, image.ImageFormat.JPEG, 8);
            let receiverSurfaceId: string = await this.receiver.getReceivingSurfaceId();
            // 创建预览流输出对象。
            let previewOutput: camera.PreviewOutput = cameraManager.createPreviewOutput(profileObj,receiverSurfaceId);
            let cameraInput : camera.CameraInput = cameraManager.createCameraInput(cameraDevices\[0\]);
            // 打开相机。
            await cameraInput.open();
            // 会话流程。
            let session : camera.PhotoSession = cameraManager.createSession(camera.SceneMode.NORMAL\_PHOTO) as camera.PhotoSession;
            // 配置会话。
            session.beginConfig();
            // 把cameraInput加入到会话。
            session.addInput(cameraInput);
            // 把预览流加入到会话。
            session.addOutput(previewOutput);
            // 提交配置信息。
            await session.commitConfig();
            // 会话开始。
            await session.start();
    
            this.receiver.on('imageArrival', () => {
               let img : image.Image = testNapi.createFromReceiver(this.receiver);
               img.release();
            })
    
         });
      }
    
      build() {
         Row() {
            Column() {
            Button("start")
               .width(100)
               .height(100)
               .onClick(() => {
                  console.info("button click in");
                  if (this.receiver == undefined) {
                     this.func();
                  }
               })
            }
            .width('100%')
         }
         .height('100%')
      }
    }
    

#### \[h2\]Native接口调用

具体接口说明请参考[Image](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/capi-image)。

在hello.cpp文件中获取JS的资源对象，并转为Native的资源对象，即可调用Native接口，调用方式示例代码如下：

**添加引用文件**

#include <multimedia/image\_framework/image\_mdk.h>
#include <multimedia/image\_framework/image\_receiver\_mdk.h>
#include <malloc.h>
#include <hilog/log.h>

static napi\_value createFromReceiver(napi\_env env, napi\_callback\_info info)
{
   size\_t argc = 1;
   napi\_value args\[2\] = {nullptr};
   napi\_get\_cb\_info(env, info, &argc, args , nullptr, nullptr);
   napi\_valuetype valuetype0;
   napi\_typeof(env, args\[0\], &valuetype0);
   napi\_ref reference;
   napi\_create\_reference(env, args\[0\], 1 ,&reference);
   napi\_value imgReceiver\_js;
   napi\_get\_reference\_value(env, reference, &imgReceiver\_js);
   
   ImageReceiverNative \* imgReceiver\_c = OH\_Image\_Receiver\_InitImageReceiverNative(env, imgReceiver\_js);

   int32\_t capacity;
   OH\_Image\_Receiver\_GetCapacity(imgReceiver\_c, &capacity);
   OH\_LOG\_Print(LOG\_APP, LOG\_INFO, 0xFF00, "\[receiver\]", "capacity: %{public}d", capacity);
   int32\_t format;
   OH\_Image\_Receiver\_GetFormat(imgReceiver\_c, &format);
   OH\_LOG\_Print(LOG\_APP, LOG\_INFO, 0xFF00, "\[receiver\]", "format: %{public}d", format);
   char \* surfaceId = static\_cast<char \*>(malloc(sizeof(char)));
   OH\_Image\_Receiver\_GetReceivingSurfaceId(imgReceiver\_c, surfaceId, sizeof(char));
   OH\_LOG\_Print(LOG\_APP, LOG\_INFO, 0xFF00, "\[receiver\]", "surfaceId: %{public}c", surfaceId\[0\]);
   OhosImageSize size;
   OH\_Image\_Receiver\_GetSize(imgReceiver\_c, &size);
   OH\_LOG\_Print(LOG\_APP, LOG\_INFO, 0xFF00, "\[receiver\]", "OH\_Image\_Receiver\_GetSize  width: %{public}d, height:%{public}d", size.width, size.height);

   napi\_value nextImage;
   // 或调用 OH\_Image\_Receiver\_ReadNextImage(imgReceiver\_c, &nextImage);
   OH\_Image\_Receiver\_ReadLatestImage(imgReceiver\_c, &nextImage);
   
   ImageNative \* nextImage\_native = OH\_Image\_InitImageNative(env, nextImage);

   OhosImageSize imageSize;
   OH\_Image\_Size(nextImage\_native, &imageSize);
   OH\_LOG\_Print(LOG\_APP, LOG\_INFO, 0xFF00, "\[receiver\]", "OH\_Image\_Size  width: %{public}d, height:%{public}d", imageSize.width, imageSize.height);

   OhosImageComponent imgComponent;
   OH\_Image\_GetComponent(nextImage\_native, 4, &imgComponent); // 4=jpeg
   
   uint8\_t \*img\_buffer = imgComponent.byteBuffer;
   
   OH\_Image\_Release(nextImage\_native);
   OH\_Image\_Receiver\_Release(imgReceiver\_c);
   return nextImage;
}