# PhotoCapture (/docs/photo-capture)





`PhotoCapture` is how a photo gets into a form: a profile picture, a badge photo, a scanned document. The visitor takes one with the camera or picks a file, crops it, and presses **Use photo**. `onChange` then receives the cropped `File`, and not before. Nothing is uploaded: the File is yours to send.

```tsx
import { PhotoCapture } from '@42-central/ui-react/photo-capture';

<PhotoCapture shape="circle" output={{ size: 512 }} onChange={(file) => setAvatar(file)} />
```

It's built from bricks you can use on their own. [Camera](/docs/camera) takes the photo, [FileTrigger](/docs/file-trigger) picks a file or opens a phone's camera app, and [ImageCropper](/docs/image-cropper) crops it. `usePhotoCapture`, a small step reducer, decides which of them is on screen. Everything the flow does, the camera turning off after a shot, the recovery steps after a refusal, the keyboard crop, comes from those bricks.

## Playground [#playground]

<story.Playground />

### Full prop browser [#full-prop-browser]

<story.WithControl />

## Basic [#basic]

**Take photo** opens the camera; **Choose a file** opens the file picker. They sit side by side at the same weight, because a camera isn't always there or allowed. The photo, taken or picked, goes straight to the cropper: taking and cropping are one step, with no review screen in between. **Retake** goes back to the camera; **Use photo** hands over the File.

<Preview code="&#x22;const [photo, setPhoto] = useState<File | null>(null);\n\n<PhotoCapture onChange={setPhoto} />&#x22;">
  <BasicDemo />
</Preview>

The camera stays off until **Take photo**, even on a site where it's already allowed. It turns off again as soon as the photo is taken, when a file is picked instead, and when `PhotoCapture` unmounts.

## The camera: live or native [#the-camera-live-or-native]

`camera` picks how the photo is taken:

| `camera`           | What happens                                                                                |
| ------------------ | ------------------------------------------------------------------------------------------- |
| `"live"`           | The camera in the page: a viewfinder with a guide, a shutter, a switch between cameras.     |
| `"native"`         | The phone's own camera app, through a file input with `capture`. No viewfinder in the page. |
| `"auto"` (default) | `native` under a coarse pointer (a phone, a tablet), `live` otherwise.                      |

The native camera app is the better camera on a phone. It focuses, exposes and stabilizes, and it never asks the browser for permission. In native mode, the first step shows two pickers: **Take photo**, with `capture`, and **Choose from library**, without it. A single picker isn't enough: Android 14 and 15 hide the camera from a picker that has no `capture`, and a picker with it hides the library. Desktop browsers ignore `capture`, so on a desktop both open the file picker.

<Preview code="`<PhotoCapture camera=&#x22;native&#x22; onChange={setPhoto} />`">
  <NativeDemo />
</Preview>

## Recipes [#recipes]

There are no presets: each use is a handful of props.

### Avatar [#avatar]

The front camera, a face guide, a circle crop, and a 512px WebP. A circle exports a square image; mask it where you show it, as [Avatar](/docs/avatar) does.

<Preview code="&#x22;<PhotoCapture\n  facing=\&#x22;user\&#x22;\n  shape=\&#x22;circle\&#x22;\n  output={{ type: 'image/webp', quality: 0.85, size: 512 }}\n  onChange={setAvatar}\n/>&#x22;">
  <AvatarDemo />
</Preview>

### ID or badge photo [#id-or-badge-photo]

A portrait ratio, and a rectangle guide in the same ratio, so the framing in the camera is the crop that comes out.

<Preview code="`<PhotoCapture facing=&#x22;user&#x22; ratio=&#x22;3/4&#x22; shape=&#x22;rectangle&#x22; output={{ size: 1200 }} onChange={setBadge} />`">
  <BadgeDemo />
</Preview>

### Document [#document]

The back camera at 4K, a free crop to trim the edges, and a large export, so the text stays readable.

<Preview code="&#x22;<PhotoCapture\n  facing=\&#x22;environment\&#x22;\n  resolution={{ width: 3840, height: 2160 }}\n  output={{ type: 'image/jpeg', quality: 0.92, size: 3000 }}\n  onChange={setScan}\n/>&#x22;">
  <DocumentDemo />
</Preview>

### Any image [#any-image]

A cover or a post: a 16/9 crop, at most 1920px wide.

<Preview code="`<PhotoCapture ratio=&#x22;16/9&#x22; output={{ size: 1920 }} onChange={setCover} />`">
  <GeneralDemo />
</Preview>

## In a modal or a drawer [#in-a-modal-or-a-drawer]

`PhotoCapture` renders inline; whether it opens in an overlay is your call. The usual layout is a [Modal](/docs/modal) on a desktop and a bottom-sheet [Drawer](/docs/drawer) on a phone, with the flow as their content. Close it from `onChange`:

<Preview code="&#x22;const phone = useMediaQuery('(width < 40rem)');\nconst capture = (\n  <PhotoCapture\n    shape=\&#x22;circle\&#x22;\n    output={{ size: 512 }}\n    onChange={(file) => {\n      setAvatar(file);\n      setOpen(false);\n    }}\n  />\n);\n\n<Button onClick={() => setOpen(true)}>Change photo</Button>\n{phone ? (\n  <Drawer open={open} onOpenChange={setOpen} placement=\&#x22;bottom\&#x22; withGrabber title=\&#x22;Profile photo\&#x22;>\n    {capture}\n  </Drawer>\n) : (\n  <Modal open={open} onOpenChange={setOpen} title=\&#x22;Profile photo\&#x22;>\n    {capture}\n  </Modal>\n)}&#x22;">
  <OverlayDemo />
</Preview>

Modal and Drawer unmount their content once closed, and `PhotoCapture` turns the camera off when it unmounts. Closing the overlay, by <kbd>Escape</kbd>, the backdrop or a swipe, turns the camera off with it. Each opening starts over at the first step.

## Output [#output]

`onChange` receives a `File` named `photo.jpg`, or for whatever type the browser actually encoded:

* **`output.type`**, `image/jpeg` by default. A browser that can't encode the type you ask for (Safari has no WebP encoder) falls back to PNG, and the File's `type` and extension say so.
* **`output.quality`**, 0–1, `0.9` by default, for JPEG and WebP.
* **`output.size`**, the longest side in px. A larger crop is scaled down to fit; a smaller one is kept as is, never scaled up.

With a `ratio`, or a circle, the File holds that ratio to the pixel: a 512px avatar is 512 × 512.

A selfie is saved the right way round, as others see you, even though the camera's preview is mirrored like a mirror. Pass `mirror` to save it as the preview shows it.

## Composable parts [#composable-parts]

`<PhotoCapture>` is one arrangement of the parts. They read a `usePhotoCapture()` of your own through `PhotoCapture.Root`, so you can lay the flow out differently, swap a button, or leave a step out:

<Preview code="&#x22;const flow = usePhotoCapture({ camera: 'live', ratio: '1/1', onChange: setPhoto });\n\n<PhotoCapture.Root flow={flow}>\n  <PhotoCapture.Source>\n    <PhotoCapture.Take variant=\&#x22;outline\&#x22; />\n    <PhotoCapture.File variant=\&#x22;outline\&#x22; />\n  </PhotoCapture.Source>\n  <PhotoCapture.Live />\n  <PhotoCapture.Crop>\n    <PhotoCapture.Retake variant=\&#x22;subtle\&#x22; />\n    <PhotoCapture.Confirm />\n  </PhotoCapture.Crop>\n</PhotoCapture.Root>&#x22;">
  <ComposedDemo />
</Preview>

`usePhotoCapture` returns plain state and handlers:

* `step` (`"source"`, `"live"` or `"crop"`), `mode` (`auto` resolved for this device), `photo`, `origin` (`"camera"`, `"native"` or `"file"`), `busy` and `failed`.
* `camera`: the `useCamera()` result behind the viewfinder, mounted with `lazy` so it only turns on with `open()`.
* `open()` opens the camera. `take(file)` is the shutter's photo. `pick(files, origin)` takes a picked file. `retake()` goes back to the camera. `confirm(crop)` exports through the cropper's `getCroppedImage` and calls `onChange`. `reset()` goes back to the first step with the camera off.

The steps themselves are a pure reducer, `reducePhotoCapture`, exported with its state and event types. An event that doesn't apply to the current step, such as a late shutter after a file was picked, or a second **Use photo** while the first is exporting, changes nothing.

| Step     | Shows                                                                                 | Leaves on                                                                             |
| -------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `source` | **Take photo** and the file picker, or in native mode the camera app and the library. | **Take photo** → `live`. A file, or a native photo → `crop`.                          |
| `live`   | The camera, its status panels and the file picker.                                    | The shutter → `crop`. A file → `crop`, the camera off.                                |
| `crop`   | The photo in the cropper, **Retake**, **Use photo**.                                  | **Retake** → `live` (or the picker again). **Use photo** → `onChange`, then `source`. |

## Privacy [#privacy]

* **Nothing leaves the page.** The kit never uploads: `onChange` gets a File, and the request is yours to make.
* **Nothing before Use photo.** Taking, retaking and cropping emit nothing.
* **The camera is on only in the live step.** It waits for **Take photo**, even when the site is already allowed. It turns off when the photo is taken, when a file is picked instead, when the page is hidden, and when `PhotoCapture` unmounts.
* **No location, no EXIF.** The File is drawn onto a canvas and encoded again, which writes no metadata. A photo picked from a phone loses its GPS position, its device and its date. Browsers apply its EXIF orientation as they draw it (`image-orientation: from-image` is the default), so a portrait photo comes out upright, without the orientation tag it no longer needs.
* **No storage.** Nothing is kept in `localStorage` or anywhere else.

## Accessibility [#accessibility]

* **Keyboard-only, start to finish.** Every control is a native button. After **Take photo**, focus moves to the shutter once the camera is live: <kbd>Space</kbd> takes the photo. Focus then moves to **Use photo**: <kbd>Enter</kbd> uses it. In between, the crop moves with the arrow keys, resizes with <kbd>Alt</kbd> and the arrows, and zooms with <kbd>+</kbd> and <kbd>-</kbd>.
* **Focus follows the steps.** **Retake** puts it back on the shutter, once the camera is live again. After **Use photo**, it returns to the first choice. It never lands on the page body because a button disappeared.
* **Every step is announced.** A polite live region says "Photo ready to crop" and "Photo added". The camera announces its own states ("Starting the camera", "Camera ready") and its failures are alerts.
* **The file picker is always there**, at the same weight as the camera: beside the camera's buttons, beside the shutter, and inside every camera panel (asking, refused, busy, no camera). Someone who can't or won't use a camera never hits a dead end.
* **Every control is named** through `translations`, including the camera's and the cropper's.
* **Reduced motion.** The shutter's flash becomes a still outline, and the cropper's fades are off.
* **Right to left.** Logical properties throughout; see below.

## Internationalization [#internationalization]

One `translations` map covers everything PhotoCapture shows: its own strings, [the camera's](/docs/camera#internationalization) and [the cropper's](/docs/image-cropper#internationalization). Under a right-to-left locale the buttons, the camera's badge and the crop controls mirror; the photo itself never does.

<Preview code="&#x22;<IntlProvider locale=\&#x22;ar-EG\&#x22;>\n  <div dir=\&#x22;rtl\&#x22; lang=\&#x22;ar\&#x22;>\n    <PhotoCapture shape=\&#x22;circle\&#x22; translations={arabic} />\n  </div>\n</IntlProvider>&#x22;">
  <DirectionDemo />
</Preview>

PhotoCapture's own keys:

| Key                             | Default                                                           |
| ------------------------------- | ----------------------------------------------------------------- |
| `sourceTitle`                   | `"Add a photo"`                                                   |
| `sourceBody`                    | `"Nothing leaves this page until you choose Use photo."`          |
| `take`                          | `"Take photo"`                                                    |
| `file`                          | `"Choose a file"`                                                 |
| `library`                       | `"Choose from library"`, in native mode                           |
| `retake`                        | `"Retake"`                                                        |
| `another`                       | `"Choose another"`, the retake for a picked file                  |
| `confirm`                       | `"Use photo"`                                                     |
| `failed`                        | `"The photo couldn't be prepared. Try again, or choose another."` |
| `announceCrop` / `announceDone` | `"Photo ready to crop"` / `"Photo added"`                         |

## Icons [#icons]

`icons` replaces any of the defaults, per slot: `take`, `file`, `retake` and `confirm`, plus the camera's `shutter`, `flip`, `start`, `retry` and `off`. Your icons are drawn as given: add `className={iconStroke}` (from `@42/ui-react`) for the kit's 1.5px line.

```tsx
<PhotoCapture icons={{ take: <Aperture className={iconStroke} />, confirm: <Upload className={iconStroke} /> }} />
```

## API [#api]

<TypeTable
  type="{
  onChange: {
    type: &#x22;(file: File) => void&#x22;,
    description: &#x22;Receives the cropped photo once Use photo is pressed. Nothing is emitted before.&#x22;,
  },
  camera: {
    type: '&#x22;live&#x22; | &#x22;native&#x22; | &#x22;auto&#x22;',
    default: '&#x22;auto&#x22;',
    description: &#x22;The camera in the page, the phone's camera app, or native under a coarse pointer and live otherwise.&#x22;,
  },
  facing: {
    type: '&#x22;user&#x22; | &#x22;environment&#x22;',
    default: '&#x22;user&#x22;',
    description: &#x22;The camera to open: the front one or the back one. Also the native picker's capture.&#x22;,
  },
  ratio: {
    type: 'number | &#x22;w/h&#x22;',
    description: &#x22;The crop's width / height, and the viewfinder's box. Free when unset; a circle is always 1.&#x22;,
  },
  shape: {
    type: '&#x22;rectangle&#x22; | &#x22;circle&#x22;',
    default: '&#x22;rectangle&#x22;',
    description: &#x22;The camera's guide and the crop.&#x22;,
  },
  mirror: {
    type: &#x22;boolean&#x22;,
    default: &#x22;false&#x22;,
    description: &#x22;Saves a selfie as the preview shows it, mirrored.&#x22;,
  },
  output: {
    type: &#x22;{ type?: string; quality?: number; size?: number }&#x22;,
    default: '{ type: &#x22;image/jpeg&#x22;, quality: 0.9 }',
    description: &#x22;The File's encoding, and its longest side in px.&#x22;,
  },
  resolution: {
    type: &#x22;{ width: number; height: number }&#x22;,
    default: &#x22;1920 × 1080&#x22;,
    description: &#x22;The capture size to aim for, for the camera in the page.&#x22;,
  },
  accept: {
    type: &#x22;string | string[]&#x22;,
    default: '&#x22;image/*&#x22;',
    description: &#x22;The file types the pickers offer.&#x22;,
  },
  color: {
    type: &#x22;Color&#x22;,
    default: '&#x22;brand&#x22;',
    description: &#x22;The palette of the buttons, the shutter, the guide and the crop.&#x22;,
  },
  translations: { type: &#x22;PhotoCaptureTranslations&#x22;, description: &#x22;See Internationalization.&#x22; },
  icons: { type: &#x22;PhotoCaptureIcons&#x22;, description: &#x22;See Icons.&#x22; },
  classNames: {
    type: &#x22;{ source?, live?, viewfinder?, crop?, viewport?, controls?, actions? }&#x22;,
    description: &#x22;Per-part classes.&#x22;,
  },
  testId: { type: &#x22;string&#x22;, description: &#x22;Renders as data-testid on the root. See [Testing](/docs/testing).&#x22; },
}"
/>

`PhotoCapture.Root` takes `flow` (a `usePhotoCapture()` result) instead of `onChange`, `camera`, `facing`, `ratio`, `resolution`, `mirror` and `output`, which go to the hook, and its own `children`.

### Parts [#parts]

| Part                   | Renders                                       | Notes                                                                                                                    |
| ---------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `PhotoCapture.Root`    | `<div>`                                       | The flow, `shape`, `accept`, translations, icons, `color`. The polite live region. Takes `asChild`.                      |
| `PhotoCapture.Source`  | `<div>`                                       | The first step. Its children replace Take and File.                                                                      |
| `PhotoCapture.Live`    | `Camera.Root`                                 | The live step: viewfinder, guide, panels, shutter, switch, picker, file. `classNames.viewfinder`, `classNames.controls`. |
| `PhotoCapture.Crop`    | `ImageCropper.Root`                           | The crop step. Its children replace Retake and Use photo, and must keep `Confirm`.                                       |
| `PhotoCapture.Take`    | A `Button`, or a `FileTrigger` in native mode | Takes Button props; `children` replace the label.                                                                        |
| `PhotoCapture.File`    | A `FileTrigger`                               | "Choose a file", or "Choose from library" in native mode.                                                                |
| `PhotoCapture.Retake`  | A `Button` or a `FileTrigger`                 | By the photo's origin: the camera, the camera app, or another file.                                                      |
| `PhotoCapture.Confirm` | A `Button`                                    | Use photo. Inside `Crop`.                                                                                                |

`usePhotoCaptureContext()` returns the flow, the translations and the icons, for a part of your own inside `PhotoCapture.Root`.

## Testing [#testing]

`testId` lands on the root, which also carries `data-step` and `data-mode`. Find the buttons by role and name: "Take photo", "Choose a file", "Retake", "Use photo". jsdom has no camera, no canvas and no layout:

* **The camera.** Give jsdom a fake `navigator.mediaDevices`, as on the [Camera page](/docs/camera#testing), then fire `loadeddata` on the video ("Camera preview") for the first frame.
* **A file.** Fire `change` on the hidden input right after the picker's button, with `{ target: { files: [file] } }`.
* **Use photo.** Ark's `getCroppedImage` needs a laid-out image and a canvas, so stub it: mock `@ark-ui/react/image-cropper`'s `useImageCropperContext` to return the real API with a `getCroppedImage` that resolves a `Blob`.

```tsx
vi.mock('@ark-ui/react/image-cropper', async (importOriginal) => {
  const original = await importOriginal<typeof import('@ark-ui/react/image-cropper')>();
  return {
    ...original,
    useImageCropperContext: () => ({
      ...original.useImageCropperContext(),
      getCroppedImage: async () => new Blob(['crop'], { type: 'image/jpeg' }),
    }),
  };
});

render(<PhotoCapture onChange={onChange} />);
const choose = screen.getByRole('button', { name: 'Choose a file' });
fireEvent.change(choose.nextElementSibling!, { target: { files: [photo] } });
await user.click(screen.getByRole('button', { name: 'Use photo' }));
expect(onChange).toHaveBeenCalledWith(expect.any(File));
```

In a real browser, Chromium's `--use-fake-device-for-media-stream` and `--use-fake-ui-for-media-stream` flags give Playwright a camera that's always allowed, and the `filechooser` event's `setFiles()` picks a file.
