Camera

The camera module helps to make camera app development easier, It provides consistency and an easy-to-use API for capturing images, and videos and storing them.

Primary Use Cases

It improves the developer experience in several key ways.

  • Handle the entire process of capturing and storing so that the developer focus more on the coding part

  • Giving more control over the camera by changing some parameters, even control over orientation

  • Support multiple captures of photos and video in a single time

Ease of use

It allows you to focus on the task you need to get done instead of managing device-specific nuances. Most common camera use cases are supported:

  • Image Capture: Save the Image

  • Video Capture: Save video and audio

Adding Module

npm install @trunpm/truvideo-capacitor-camera-sdk --registry=https://registry.npmjs.org/ --//registry.npmjs.org/:_authToken=<YOUR_TOKEN>

Import the following dependency in your file, here you will use these function.

import { 
    LensFacing, 
    FlashMode, 
    Orientation, 
    CameraMode, 
    initCameraScreen,
    ImageFormat, 
    type CameraConfiguration     
} from '@trunpm/truvideo-capacitor-camera-sdk';

Required permissions

For Android :

To access the camera and microphone in the Android app, you have to include some of the necessary permissions in your AndroidManifest.xml file. These permission are

<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

For iOS :

For accessing the camera and microphone in the iOS app, you have to include some of the necessary permissions in your Info.plist file. Here are the basic steps:

  1. Open your Xcode project.

  2. Locate the Info.plist file in the Project Navigator.

  3. Right-click on the Info.plist file and select "Open As" > "Source Code".

  4. Add the following keys and descriptions inside the <dict> tag:

<key>NSCameraUsageDescription</key>
<string>We need access to your camera to capture photos.</string>
<key>NSMicrophoneUsageDescription</key>
<string>We need access to your microphone to record audio.</string>
  1. Save the Info.plist file and switch back to the standard editor view if necessary.

For detailed instructions, you can refer to Apple's official documentation “Requesting authorization to capture and save media“ here.

Camera Configuration

Camera initialization requires camera configuration, Which we have to pass as a argument in initCameraScreen function. CameraConfiguration defines the settings for the camera, like lens facing direction, flash mode, orientation, output path, camera mode etc. This configuration allows developers to customize the camera's behavior and output to meet specific application needs.

const cameraConfiguration = {
    lensFacing: LensFacing?.Front || "front",
    //lensFacing: LensFacing?.Back,
    flashMode: FlashMode?.Off || "off",
    //flashMode: FlashMode?.On
    orientation: Orientation?.Portrait || "portrait",
    //orientation: Orientation?.LandscapeLeft,
    //orientation: Orientation?.LandscapeRight,
    //orientation: Orientation?.Portrai
    outputPath: "",
    frontResolutions: [],
    frontResolution: null,
    backResolutions: [],
    backResolution: null,
    mode: CameraMode.videoAndImage(),
    //mode: CameraMode.image()
    //mode: CameraMode.video()
    imageFormat : ImageFormat.PNG
  }

Output path will be responsible for where will be the recorded media will be placed in the app’s package

Camera Initialization

TruVideoCameraSdk is SDK containing the methods required to work with the camera module these are:-

Typed Checked Method :

async function openCamera() {
    try {
      // cameraConfiguration will be the formattedcameraConfiguration from above 
      const response : CameraResult[]  = await initCameraScreenTS(cameraConfiguration);

    } catch (error) {
      console.error("Camera error:", error);
    }
  }
  
// Camera response format import from Camera module
interface CameraResult {
  id: string,
  createdAt: number,
  filePath: string,
  type: string,
  lensFacing: string,
  orientation: string,
  resolution: Resolution,
  duration: number,
}

JSON response method :

async function openCamera() {
    try {
      // cameraConfiguration will be the formattedcameraConfiguration from above 
      const response = await initCameraScreen(cameraConfiguration);
      const resultData = response.value;

      let mediaItems: any[] = [];

      if (typeof resultData === "string") {
        try {
          const parsed = JSON.parse(resultData);
          mediaItems = Array.isArray(parsed) ? parsed : [];
        } catch (error) {
          console.error("[openCamera] Failed to parse resultData:", error);
          return;
        }
      }

      if (!Array.isArray(mediaItems)) {
        console.error("[openCamera] Error: mediaItems is not an array:", mediaItems);
        return;
      }

    } catch (error) {
      console.error("Camera error:", error);
    }
  }

Note The Camera module can run into errors if used by itself because it depends on a shared component. The Video module also uses this same component, and to avoid conflicts, TruVideo manages it within the Video module. This means:

  • If you use only the Camera module → errors may occur.

  • If you use the Camera and Video modules together → everything works smoothly, since the shared component is managed centrally.

Media Item Object

The result contains an array of MediaItem objects, where each MediaItem represents a media file (e.g., video) captured or stored by the application. Below is a description of the properties included in each MediaItem object.

Property
Type
Description

id

Number

A unique identifier for the media.

filePath

String

The file path where the media item is stored on the device.

duration

Number

The duration of the media item in milliseconds (0 for images).

orientation

String

The orientation of the media item (PORTRAIT or LANDSCAPE).

lensFacing

String

The camera lens used to capture the media (BACK or FRONT).

resolution

Object

An object containing the dimensions of the media item (width and height).

createdAt

Number

The timestamp (in milliseconds) when the media item was created.

Recieve Camera Event -

useEffect(() => {
  const eventEmitter = new NativeEventEmitter(NativeModules.TruVideoReactMediaSdk);

  const cameraListener = TruvideoSdkCamera.addListener("cameraEvent", (event) => {
        console.log("Received Camera Event:", event.cameraEvent);
      });

  return () => {
    // remove emitter when not required
    cameraListener.remove();
  };
}, []);

Lens Facing

The LensFacing enum specifies the camera's direction, with two possible values:

  • LensFacing.Front: Uses the front-facing camera.

  • LensFacing.Back: Uses the back-facing camera.

export const LensFacing = {
  Back: 'Back',
  Front: 'Front'
}

Image Format

The FlashMode enum controls the flash behavior during media capture, with two options:

  • ImageFormat.JPEG: Enables the flash.

  • ImageFormat.PNG: Disables the flash.

export const ImageFormat = {
  JPEG: 'jpeg',
  PNG: 'png'
}

Flash Mode

The FlashMode enum controls the flash behavior during media capture, with two options:

  • FlashMode.On: Enables the flash.

  • FlashMode.Off: Disables the flash.

export const FlashMode = {
  On: 'On',
  Off: 'Off'
}

Orientation

The Orientation enum defines the camera's orientation for media capture. It includes four modes, or can be set to null for automatic orientation:

  • Orientation.Portrait: Standard portrait orientation.

  • Orientation.LandscapeLeft: Landscape with the left side up.

  • Orientation.LandscapeRight: Landscape with the right side up.

  • Orientation.PortraitReverse: Portrait with the top inverted.

export const Orientation = {
  Portrait: 'Portrait',
  LandscapeLeft: 'LandscapeLeft',
  LandscapeRight: 'LandscapeRight',
  PortraitReverse: 'PortraitReverse'
}

Camera Mode

The CameraMode enum determines the capture mode of the camera, with three options:

  • CameraMode.image(): Configures the camera to capture only images, disabling video recording.

  • CameraMode.video(): Configures the camera to capture only videos, disabling image capture.

  • CameraMode.videoAndImage(): Configures the camera to support both video and image capture.

  • CameraMode.singleImage(): configures capture of one picture. Returns a TruvideoSdkCameraMediaMode instance.

  • CameraMode.singleVideo(): configures capture of one video with an optional duration limit (null for no limit). Returns a TruvideoSdkCameraMediaMode instance.

  • CameraMode.singleVideoOrImage(): configures capture of either one video or one picture with an optional video duration limit (null for no limit). Returns a TruvideoSdkCameraMediaMode instance.

  • CameraMode.videoAndImage(): configures capture of videos and pictures with optional parameters: videoCount (maximum videos, null for no limit), pictureCount (maximum pictures, null for no limit), and videoDuration (maximum video duration in seconds, null for no limit). Returns the instance of TruvideoSdkCameraMediaMode.

  • CameraMode.singleMedia(): configures capture of videos and pictures with parameters: mediaCount (strict maximum combined videos and pictures) and videoDuration (maximum video duration in seconds, null for no limit). Returns a TruvideoSdkCameraMediaMode instance.

export class CameraMode {
  static singleMedia(durationLimit?: number,mediaCount?: number)
  static videoAndImage(durationLimit?: number,videoMaxCount?: number,imageMaxCount?: number)
  static singleVideo(durationLimit?: number)
  static singleImage()
  static singleVideoOrImage(durationLimit?: number)
  static video(videoMaxCount?: number,durationLimit?: number)
  static image(imageMaxCount?: number)
}

Last updated

Was this helpful?