> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Images, videos and saving

Crop and copy images with `createImageBitmap()`, draw a video's frame, and save what a [`<canvas>`](/api/elements/canvas.md) shows as a JPEG or PNG. It all works as on the web, and the phone handles the pixels.

## Save as an image

`toBlob()` and `toDataURL()` work as on an HTML canvas. They encode what the canvas shows:

```typescript
canvas.toBlob(
  (blob) => {
    if (blob) this.photo.set(URL.createObjectURL(blob));
  },
  'image/jpeg',
  0.9,
);
```

- **The type:** a PNG, or a JPEG for `'image/jpeg'`. Any other type gives a PNG, as in browsers.
- **The quality:** from 0 to 1, for a JPEG. It's 0.92 when you don't give one.
- **The `Blob`** is ready to show in an `<image>`, upload, or [share](/guide/share.md).

**The phone encodes the image, so it's quick.** A 2048 by 1365 JPEG takes about 20 ms on the iOS Simulator and 35 ms on the Android emulator. The callback has the `Blob` about 15 ms after that. A PNG of that size is slower: around 100 ms on the iOS Simulator and 300 ms on the Android emulator. It's several times larger, too.

### Things to know

- **With WebGL, call it right after you draw.** A 2D canvas keeps what's drawn on it. WebGL clears the drawing buffer once a frame is on screen, as in a browser. So call `toBlob()` in the function that draws, such as right after three.js's `renderer.render()`. Or make the context with `preserveDrawingBuffer: true` (three.js: `new WebGLRenderer({ preserveDrawingBuffer: true })`). Called later without it, you get a transparent image.
- **The callback runs later,** as on the web. `toBlob()` reads the canvas when you call it, and the callback gets the `Blob` once it's ready. `toDataURL()` returns at once.
- **A JPEG has no transparency.** Transparent pixels come out black, as in browsers. A PNG keeps them.
- **A canvas without a context** encodes as a transparent image of its size, as in browsers.
- **Nothing to encode gives `null`** from `toBlob()`, or `'data:,'` from `toDataURL()`. That's a canvas with no width or height, one whose context was lost, or [Lynx Explorer](/guide/glossary.md#lynx-explorer), which has no canvas.
- **Prefer `toBlob()`.** A `data:` URL holds the image as text a third larger than the file, and it's built all at once.
- **Encoding makes the [main thread](/guide/glossary.md#main-thread) wait** while the phone reads and encodes the canvas: tens of milliseconds for a photo. A browser's `toBlob()` encodes in the background.

## Draw a video frame

A [`<video>`](/api/elements/video.md) is an image too. Draw its frame for a thumbnail or a filter, or play it on a three.js mesh with **`VideoTexture`**:

```typescript title="src/app/thumbnail.ts"
import { Component, type ElementRef, viewChild } from '@angular/core';
import { LYNX_ELEMENTS, type LynxCanvasElement } from '@blotch/angular-lynx';

@Component({
  selector: 'app-thumbnail',
  imports: [LYNX_ELEMENTS],
  template: `
    <video
      #video
      src="https://example.com/clip.mp4"
      class="h-[180px] w-full"
      (bindfirstframe)="grab()"
    ></video>
    <canvas #thumb width="160" height="90" class="h-[90px] w-[160px]"></canvas>
  `,
})
export class Thumbnail {
  readonly video = viewChild.required<ElementRef<HTMLVideoElement>>('video');
  readonly thumb = viewChild.required<ElementRef<LynxCanvasElement>>('thumb');

  grab(tries = 10): void {
    const video = this.video().nativeElement;
    // Draw only once there's a frame: try again a little later until then.
    if (video.readyState < video.HAVE_CURRENT_DATA) {
      if (tries > 0) setTimeout(() => this.grab(tries - 1), 100);
      return;
    }
    const canvas = this.thumb().nativeElement as unknown as HTMLCanvasElement;
    canvas.getContext('2d')!.drawImage(video, 0, 0, 160, 90);
  }
}
```

For a mesh, pass the same element to three.js: `new THREE.VideoTexture(video)`. It waits for the frame by itself.

- **The pixels never pass through JavaScript.** The phone reads the frame the video shows. `createImageBitmap(video)` keeps a copy of it, as on the web.
- **Before its first frame,** `videoWidth` is 0, `readyState` is `HAVE_NOTHING`, and nothing is drawn, as in a browser.
- **Check `readyState` before you draw**, and try again if there's no frame yet, as above. A video draws its frame only once it has one (`readyState` at least `HAVE_CURRENT_DATA`), whether it's shown or hidden with `display: none`.
- **A turned video is drawn turned.** When the file says to turn it (a phone recording in portrait), it's drawn as it plays. `videoWidth` and `videoHeight` are its turned size, as in a browser.

### When `bindfirstframe` arrives

- **On the phone**, the frame is usually there when `bindfirstframe` arrives. iOS waits for it for half a second at most, and Android for 5 seconds. Then each sends the event anyway.
- **The [web preview](/guide/glossary.md#web-preview) never sends `bindfirstframe`.** Draw from a tap or a `bindtimeupdate` there.

### In the web preview

The web preview takes a template's `<video>` and `<canvas>` too. The browser's `drawImage()`, `createPattern()`, `texImage2D()`, `texSubImage2D()` and `createImageBitmap()` read the element itself.

There, as on the phone, `instanceof` checks pass:

- The video is `instanceof HTMLVideoElement`. three.js sizes a `VideoTexture` by it.
- The canvas is `instanceof HTMLCanvasElement`.
- Its 2D context is `instanceof CanvasRenderingContext2D`.
- Its WebGL2 context is `instanceof WebGL2RenderingContext`. The objects it makes are instances of `WebGLBuffer`, `WebGLTexture`, `WebGLProgram`, `WebGLUniformLocation` and the rest, as WebGL helper libraries such as twgl.js check.

## Crop with createImageBitmap

`createImageBitmap()` takes the same sources as on the web. With the crop arguments, it makes a bitmap of a part of one:

```typescript
// The second 32 by 32 sprite of a sprite sheet.
const sprite = await createImageBitmap(sheet, 32, 0, 32, 32);
```

- **Any source can be cropped:** a `Blob`, a loaded `Image`, a canvas, an `ImageBitmap` or an `ImageData`. A canvas is a `<canvas>`, `document.createElement('canvas')` or an `OffscreenCanvas`.
- **Outside the source is transparent.** The part of the crop rectangle past the source's edge comes out clear.
- **An `ImageBitmap` is copied** with the options you pass: flipped, premultiplied or resized.
- **The phone copies the pixels.** A canvas, a bitmap or an `Image` is copied from the pixels the phone already has. Nothing crosses to JavaScript, and no file is decoded again. An `ImageData`'s pixels go to the phone once.
- **`OffscreenCanvas.transferToImageBitmap()`** hands over its image and clears the canvas, as on the web.
- **Make a WebGL canvas's bitmap in the function that draws**, as with [`toBlob()`](#save-as-an-image). Once the frame is on screen, its drawing buffer is cleared, unless you asked for `preserveDrawingBuffer: true`.

## Show an ImageBitmap

`getContext('bitmaprenderer')` gives an `ImageBitmapRenderingContext`, as on the web. Its `transferFromImageBitmap()` shows an `ImageBitmap` in the canvas. That's how web code shows what an `OffscreenCanvas` drew:

```typescript
const offscreen = new OffscreenCanvas(width, height);
const context = offscreen.getContext('2d')!;
// ... draw the frame ...
const visible = this.canvas().nativeElement.getContext(
  'bitmaprenderer',
) as ImageBitmapRenderingContext;
visible.transferFromImageBitmap(offscreen.transferToImageBitmap());
```

- **The bitmap is scaled to the canvas's CSS size**, whatever its `width` and `height`. The canvas draws, uploads and encodes as that bitmap.
- **The bitmap is handed over, not copied.** Afterwards its `width` and `height` are 0, and it can't be drawn or shown again.
- **`transferFromImageBitmap(null)` clears the canvas** to transparent. It's black for a context made with `{ alpha: false }`.

## In an ejected app

An ejected app keeps the native shell it was ejected with. An older shell lacks some of this:

- **`createImageBitmap()`** rejects an `ImageBitmap`, an `ImageData`, a loaded `Image` and a crop.
- **`getContext('bitmaprenderer')`** stays `null`: the shell has no bitmaprenderer context.

To take these in without losing your own native changes, merge the new canvas files from `node_modules/@blotch/angular-lynx-native/templates` into your copy:

- **iOS:** `App/AngularLynxWebGL.h`, `App/AngularLynxWebGL.m` and `App/AngularLynxBitmapRendererContext.m`
- **Android:** `WebGLModule.kt`, `Canvas2DContext.kt`, `BitmapRendererContext.kt` and `BitmapPresenter.kt`

The module uses the bitmaprenderer context's classes, so copying it alone doesn't build.

## Related

- [Draw on a canvas](/guide/canvas/index.md): 2D drawing, and what the build includes
- [Draw in 3D](/guide/canvas/3d.md): three.js, angular-three, textures and models
- [Share Files and Links](/guide/share.md): send a canvas's image to another app, or save it to Photos
- [Darkroom](/examples/darkroom.md): a photo editor that develops in WebGL and exports with `toBlob()`
- [`<canvas>`](/api/elements/canvas.md) and [`<video>`](/api/elements/video.md)
