Skip to content

Camera

The camera capability shows the system camera screen or a live preview you control. See the Camera guide for setup and platform differences.

The device camera: the system capture screen, or a live preview you control.

Enable it in pythonnative.toml. Declare microphone as well if you record video with sound:

[plugins]
use = ["camera"]

[permissions]
camera = "Scan receipts with your camera."
microphone = "Record sound with your videos."
Example
import pythonnative as pn
from pythonnative.camera import Barcode, Camera, CameraView

async def snap() -> None:
    path = await Camera.take_photo(quality=0.8)
    if path is not None:
        await upload(path)

@pn.component
def Scanner() -> pn.Node:
    camera = pn.use_ref()

    async def capture() -> None:
        photo = await camera.current.take_picture(quality=0.8)
        print(photo.path, photo.width, photo.height)

    def scanned(barcode: Barcode) -> None:
        print(barcode.type, barcode.data)

    return pn.Column(
        CameraView(
            ref=camera,
            barcode_types=["qr", "ean13"],
            on_barcode=scanned,
            style=pn.style(flex=1),
        ),
        pn.Button("Capture", on_press=capture),
    )

Classes:

Name Description
Photo

A picture taken by a CameraView.

VideoRecording

A video recorded by a CameraView.

Barcode

A barcode a CameraView saw.

CameraError

Why a CameraView can't show the camera.

CameraViewProps

Props of CameraView, which documents them.

CameraViewHandle

Handle for CameraView, published on its ref.

Camera

The system camera screen.

Functions:

Name Description
CameraView

Show a live camera preview: AVFoundation on iOS, CameraX on Android.

Attributes:

Name Type Description
CameraFacing

Which lens a CameraView uses.

CameraFlash

on and auto fire when a picture is taken; torch stays lit.

BarcodeType

A barcode symbology. codabar needs iOS 15.4 or later.

CameraFacing module-attribute

CameraFacing = Literal['back', 'front']

Which lens a CameraView uses.

CameraFlash module-attribute

CameraFlash = Literal['off', 'on', 'auto', 'torch']

on and auto fire when a picture is taken; torch stays lit.

BarcodeType module-attribute

BarcodeType = Literal[
    "aztec",
    "codabar",
    "code128",
    "code39",
    "code93",
    "data_matrix",
    "ean13",
    "ean8",
    "itf14",
    "pdf417",
    "qr",
    "upc_a",
    "upc_e",
]

A barcode symbology. codabar needs iOS 15.4 or later.

Photo dataclass

Photo(path: str, width: int, height: int)

A picture taken by a CameraView.

Attributes:

Name Type Description
path str

The JPEG in the app's cache directory.

width int

Pixels across, as the picture displays.

height int

Pixels down, as the picture displays.

VideoRecording dataclass

VideoRecording(path: str, duration: float)

A video recorded by a CameraView.

Attributes:

Name Type Description
path str

The video file in the app's cache directory: QuickTime (.mov) on iOS, MPEG-4 (.mp4) on Android, and a blob: URL in the browser preview.

duration float

Seconds recorded.

Barcode dataclass

Barcode(type: BarcodeType, data: str)

A barcode a CameraView saw.

Attributes:

Name Type Description
type BarcodeType

Its symbology.

data str

The decoded text.

CameraError dataclass

CameraError(code: str, message: str)

Why a CameraView can't show the camera.

Attributes:

Name Type Description
code str

unavailable when the device has no such camera (the iOS simulator has none at all), permission_denied when the user refused, or capture_failed when the session stopped working.

message str

A description for logs, not for end users.

CameraViewProps dataclass

CameraViewProps(
    facing: CameraFacing = "back",
    flash: CameraFlash = "off",
    zoom: float = 1.0,
    barcode_types: Optional[List[BarcodeType]] = None,
    on_barcode: Optional[Callable[[Barcode], Any]] = None,
    on_ready: Optional[Callable[[], Any]] = None,
    on_error: Optional[Callable[[CameraError], Any]] = None,
    accessibility_label: Annotated[
        Optional[str], NativeField()
    ] = None,
    test_id: Annotated[Optional[str], NativeField()] = None,
)

Props of CameraView, which documents them.

CameraViewHandle

CameraViewHandle(tag: int, type_name: str, backend: Any)

Bases: ViewHandle

Handle for CameraView, published on its ref.

Every method raises NativeModuleError with a code: not_ready when the camera isn't running, permission_denied when a required permission was refused, busy for a conflicting capture, or capture_failed. Off device, the fallback returns a record with an empty path.

Methods:

Name Description
take_picture

Take a picture and save it as a JPEG in the app's cache directory.

start_recording

Start recording video, returning once frames are being written.

stop_recording

Stop recording and wait for the file to be finished.

take_picture async

take_picture(*, quality: float = 0.9) -> Photo

Take a picture and save it as a JPEG in the app's cache directory.

Parameters:

Name Type Description Default
quality float

JPEG quality from 0 to 1.

0.9

Returns:

Type Description
Photo

The saved picture.

start_recording async

start_recording(*, audio: bool = True) -> None

Start recording video, returning once frames are being written.

Parameters:

Name Type Description Default
audio bool

Capture sound, prompting for the microphone permission, which the app must declare under [permissions]. Refusing it raises rather than silently recording without sound. Pass False to record silent video and skip the prompt.

True

stop_recording async

stop_recording() -> VideoRecording

Stop recording and wait for the file to be finished.

Returns:

Type Description
VideoRecording

The saved video.

Raises:

Type Description
NativeModuleError

With the code not_recording when nothing is being recorded, or capture_failed when no video was saved (some platforms reject a recording too short to have a frame).

Camera

The system camera screen.

Raises:

Type Description
NativeModuleError

If the native module fails, or with the code plugin_not_enabled when camera isn't in the build.

Methods:

Name Description
take_photo

Open the system camera screen and let the user take a photo.

take_photo async staticmethod

take_photo(
    *, quality: float = 0.9, allow_editing: bool = False
) -> Optional[str]

Open the system camera screen and let the user take a photo.

Android asks for the camera permission first, because the system refuses this screen to an app that declares it without holding it.

Parameters:

Name Type Description Default
quality float

JPEG quality from 0 to 1.

0.9
allow_editing bool

Show the crop editor before saving, on iOS. Android has no system crop screen and ignores this.

False

Returns:

Type Description
Optional[str]

The path of a full-size JPEG in the app's cache directory, or

Optional[str]

None when the user canceled or refused the permission, or the

Optional[str]

device has no camera (such as the iOS simulator).

Raises:

Type Description
NativeModuleError

With the code busy when the screen is already open.

CameraView

CameraView(
    *children: Node,
    facing: CameraFacing = "back",
    flash: CameraFlash = "off",
    zoom: float = 1.0,
    barcode_types: Optional[Sequence[BarcodeType]] = None,
    on_barcode: Optional[Callable[[Barcode], Any]] = None,
    on_ready: Optional[Callable[[], Any]] = None,
    on_error: Optional[Callable[[CameraError], Any]] = None,
    accessibility_label: Optional[str] = None,
    test_id: Optional[str] = None,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None
) -> Element

Show a live camera preview: AVFoundation on iOS, CameraX on Android.

A preview has no intrinsic size, so give it one with style, such as pn.style(flex=1) or pn.style(height=240). Passing a ref publishes a CameraViewHandle on ref.current.

It prompts for the camera permission when it first appears. It never raises for a missing camera or a refused prompt: it shows a placeholder and calls on_error, which is what happens on the iOS simulator. Android runs one preview at a time, so the CameraView shown most recently wins.

Parameters:

Name Type Description Default
*children Node

Elements to draw on top of the preview, such as a scan frame.

()
facing CameraFacing

The lens to use.

'back'
flash CameraFlash

The flash mode. A device without a flash ignores it.

'off'
zoom float

Magnification, where 1 is none. It's clamped to what the current lens supports.

1.0
barcode_types Optional[Sequence[BarcodeType]]

The symbologies to look for. Scanning runs only when this isn't empty, and costs nothing otherwise.

None
on_barcode Optional[Callable[[Barcode], Any]]

Called with a Barcode when one comes into view, and for the same text again only after it has been out of view for a moment.

None
on_ready Optional[Callable[[], Any]]

Called each time the preview starts.

None
on_error Optional[Callable[[CameraError], Any]]

Called with a CameraError when the camera can't run.

None
accessibility_label Optional[str]

Screen reader label for the preview.

None
test_id Optional[str]

Identifier for UI tests.

None
style StyleProp

Layout and visual style.

None
ref Optional[Ref]

Optional Ref from use_ref().

None
key Optional[str]

Stable identity among siblings.

None

Returns:

Type Description
Element

The preview element.

Raises:

Type Description
PluginNotEnabledError

On a device whose build doesn't include camera.