ImageDefinition

ImageDefinition is a specialized CoValue designed specifically for managing images in Jazz applications. It extends beyond basic file storage by supporting a blurry placeholder, built-in resizing, and progressive loading patterns.

Beyond ImageDefinition, Jazz offers higher-level functions and components that make it easier to use images:

Creating Images

The easiest way to create and use images in your Jazz application is with the createImage() function:

The createImage() function:

  • Creates an ImageDefinition with the right properties
  • Generates a small placeholder for immediate display
  • Creates multiple resolution variants of your image
  • Returns the created ImageDefinition

Configuration Options

declare function 
function createImage(image: Blob | File | string, options: {
    owner?: Group | Account;
    placeholder?: "blur" | false;
    maxSize?: number;
    progressive?: boolean;
}): Loaded<typeof ImageDefinition, {
    original: true;
}>
createImage
(
image: string | Blob | Fileimage: Blob | File | string,
options: {
    owner?: Group | Account;
    placeholder?: "blur" | false;
    maxSize?: number;
    progressive?: boolean;
}
options
: {
owner?: Group | Account | undefinedowner?: class Group
@categoryIdentity & Permissions
Group
| class Account
@categoryIdentity & Permissions
Account
;
placeholder?: false | "blur" | undefinedplaceholder?: "blur" | false; maxSize?: number | undefinedmaxSize?: number; progressive?: boolean | undefinedprogressive?: boolean; }):
type Loaded<T extends CoValueClassOrSchema, R extends ResolveQuery<T> = true> = R extends boolean | undefined ? NonNullable<InstanceOfSchemaCoValuesNullable<T>> : [NonNullable<InstanceOfSchemaCoValuesNullable<T>>] extends [...] ? Exclude<...> extends CoValue ? R extends {
    ...;
} ? readonly ((CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & Exclude<...> : [...] extends [...] ? Exclude<...> extends CoValue ? ItemDepth extends {
    ...;
} ? readonly ((CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & Exclude<...> : [...] extends [...] ? Exclude<...> extends CoValue ? ItemDepth extends {
    ...;
} ? readonly ((CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & Exclude<...> : [...] extends [...] ? Exclude<...> extends CoValue ? ItemDepth extends {
    ...;
} ? readonly ((CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & Exclude<...> : [...] extends [...] ? Exclude<...> extends CoValue ? ItemDepth extends {
    ...;
} ? readonly ((CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & Exclude<...> : [...] extends [...] ? Exclude<...> extends CoValue ? ItemDepth extends {
    ...;
} ? readonly ((CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & Exclude<...> : [...] extends [...] ? Exclude<...> extends CoValue ? ItemDepth extends {
    ...;
} ? readonly ((CoValue & ... 1 more ... & (ItemDepth extends boolean | undefined ? CoValue & Exclude<...> : [...] extends [...] ? Exclude<...> extends CoValue ? ItemDepth extends {
    ...;
} ? readonly ((CoValue & ... 1 more ... & (ItemDepth extends boolean ...
Loaded
<
typeof
const ImageDefinition: CoMapSchema<{
    original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema;
    originalSize: ZodTuple<[ZodNumber, ZodNumber], null>;
    placeholderDataURL: ZodOptional<ZodString>;
    progressive: ZodBoolean;
}, FileStreamSchema, Group | Account>
@categoryMedia
ImageDefinition
,
{ original: trueoriginal: true } >

image

The image to create an ImageDefinition from.

This can be a Blob or a File.

owner

The owner of the ImageDefinition. This is used to control access to the image. See Groups as permission scopes for more information on how to use groups to control access to images.

placeholder

The placeholder is a base64 encoded image that is displayed while the image is loading. Currently, only "blur" is a supported.

maxSize

The image generation process includes a maximum size setting that controls the longest side of the image. A built-in resizing feature is applied based on this setting.

progressive

The progressive loading pattern is a technique that allows images to load incrementally, starting with a small version and gradually replacing it with a larger version as it becomes available. This is useful for improving the user experience by showing a placeholder while the image is loading.

Passing progressive: true to createImage() will create internal smaller versions of the image for future uses.

Create multiple resized copies

To create multiple resized copies of an original image for better layout control, you can use the createImage function multiple times with different parameters for each desired size. Here’s an example of how you might implement this:

import { import coco } from "jazz-tools";
import { function createImage(imageBlobOrFile: Blob | File, options?: CreateImageOptions): Promise<CreateImageReturnType> (+1 overload)
Creates an ImageDefinition from an image file or blob with built-in UX features. This function creates a specialized CoValue for managing images in Jazz applications. It supports blurry placeholders, built-in resizing, and progressive loading patterns.
@returnsPromise that resolves to an ImageDefinition@example```ts import { createImage } from "jazz-tools/media"; // Create an image from a file input async function handleFileUpload(event: React.ChangeEvent<HTMLInputElement>) { const file = event.target.files?.[0]; if (file) { // Creates ImageDefinition with a blurry placeholder, limited to 1024px // on the longest side, and multiple resolutions automatically const image = await createImage(file, { owner: me.$jazz.owner, maxSize: 1024, placeholder: "blur", progressive: true, }); // Store the image in your application data me.profile.image = image; } } ``` ```
createImage
} from "jazz-tools/media";
// Jazz Schema const
const ProductImage: co.Map<{
    image: co.Map<{
        original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema;
        originalSize: ZodTuple<[ZodNumber, ZodNumber], null>;
        placeholderDataURL: ZodOptional<ZodString>;
        progressive: ZodBoolean;
    }, co.FileStream, Group | Account>;
    thumbnail: co.Map<...>;
}, unknown, Group | Account>
ProductImage
= import coco.
map<{
    image: co.Map<{
        original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema;
        originalSize: ZodTuple<[ZodNumber, ZodNumber], null>;
        placeholderDataURL: ZodOptional<ZodString>;
        progressive: ZodBoolean;
    }, co.FileStream, Group | Account>;
    thumbnail: co.Map<...>;
}>(shape: {
    ...;
}): co.Map<...>
export map
map
({
image: co.Map<{
    original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema;
    originalSize: ZodTuple<[ZodNumber, ZodNumber], null>;
    placeholderDataURL: ZodOptional<ZodString>;
    progressive: ZodBoolean;
}, co.FileStream, Group | Account>
image
: import coco.
function image(): co.Image
export image
image
(),
thumbnail: co.Map<{
    original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema;
    originalSize: ZodTuple<[ZodNumber, ZodNumber], null>;
    placeholderDataURL: ZodOptional<ZodString>;
    progressive: ZodBoolean;
}, co.FileStream, Group | Account>
thumbnail
: import coco.
function image(): co.Image
export image
image
(),
}); const
const mainImage: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & {
    ...;
} & CoMap, {
    ...;
}, 10, []>
mainImage
= await function createImage(imageBlobOrFile: Blob | File, options?: CreateImageOptions): Promise<CreateImageReturnType> (+1 overload)
Creates an ImageDefinition from an image file or blob with built-in UX features. This function creates a specialized CoValue for managing images in Jazz applications. It supports blurry placeholders, built-in resizing, and progressive loading patterns.
@returnsPromise that resolves to an ImageDefinition@example```ts import { createImage } from "jazz-tools/media"; // Create an image from a file input async function handleFileUpload(event: React.ChangeEvent<HTMLInputElement>) { const file = event.target.files?.[0]; if (file) { // Creates ImageDefinition with a blurry placeholder, limited to 1024px // on the longest side, and multiple resolutions automatically const image = await createImage(file, { owner: me.$jazz.owner, maxSize: 1024, placeholder: "blur", progressive: true, }); // Store the image in your application data me.profile.image = image; } } ``` ```
createImage
(const myBlob: BlobmyBlob);
const
const thumbnail: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & {
    ...;
} & CoMap, {
    ...;
}, 10, []>
thumbnail
= await function createImage(imageBlobOrFile: Blob | File, options?: CreateImageOptions): Promise<CreateImageReturnType> (+1 overload)
Creates an ImageDefinition from an image file or blob with built-in UX features. This function creates a specialized CoValue for managing images in Jazz applications. It supports blurry placeholders, built-in resizing, and progressive loading patterns.
@returnsPromise that resolves to an ImageDefinition@example```ts import { createImage } from "jazz-tools/media"; // Create an image from a file input async function handleFileUpload(event: React.ChangeEvent<HTMLInputElement>) { const file = event.target.files?.[0]; if (file) { // Creates ImageDefinition with a blurry placeholder, limited to 1024px // on the longest side, and multiple resolutions automatically const image = await createImage(file, { owner: me.$jazz.owner, maxSize: 1024, placeholder: "blur", progressive: true, }); // Store the image in your application data me.profile.image = image; } } ``` ```
createImage
(const myBlob: BlobmyBlob, {
maxSize?: number | undefined
Maximum size constraint for the image. The image will be resized to fit within this size while maintaining aspect ratio. If the image is smaller than maxSize in both dimensions, no resizing occurs.
@example1024 // Resizes image to fit within 1024px in the largest dimension
maxSize
: 100,
}); // or, in case of migration, you can use the original stored image. const
const newThumb: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & {
    ...;
} & CoMap, {
    ...;
}, 10, []>
newThumb
= await function createImage(imageBlobOrFile: Blob | File, options?: CreateImageOptions): Promise<CreateImageReturnType> (+1 overload)
Creates an ImageDefinition from an image file or blob with built-in UX features. This function creates a specialized CoValue for managing images in Jazz applications. It supports blurry placeholders, built-in resizing, and progressive loading patterns.
@returnsPromise that resolves to an ImageDefinition@example```ts import { createImage } from "jazz-tools/media"; // Create an image from a file input async function handleFileUpload(event: React.ChangeEvent<HTMLInputElement>) { const file = event.target.files?.[0]; if (file) { // Creates ImageDefinition with a blurry placeholder, limited to 1024px // on the longest side, and multiple resolutions automatically const image = await createImage(file, { owner: me.$jazz.owner, maxSize: 1024, placeholder: "blur", progressive: true, }); // Store the image in your application data me.profile.image = image; } } ``` ```
createImage
(
const mainImage: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & {
    ...;
} & CoMap, {
    ...;
}, 10, []>
mainImage
!.original: FileStreamoriginal!.
FileStream.toBlob(options?: {
    allowUnfinished?: boolean;
}): Blob | undefined
toBlob
()!, {
maxSize?: number | undefined
Maximum size constraint for the image. The image will be resized to fit within this size while maintaining aspect ratio. If the image is smaller than maxSize in both dimensions, no resizing occurs.
@example1024 // Resizes image to fit within 1024px in the largest dimension
maxSize
: 100,
}); const
const imageSet: {
    readonly image: {
        readonly original: FileStream;
        readonly originalSize: [number, number];
        readonly placeholderDataURL: string | undefined;
        readonly progressive: boolean;
    } & {
        ...;
    } & CoMap;
    readonly thumbnail: {
        readonly original: FileStream;
        readonly originalSize: [number, number];
        readonly placeholderDataURL: string | undefined;
        readonly progressive: boolean;
    } & ... 1 more ... & CoMap;
} & CoMap
imageSet
=
const ProductImage: co.Map<{
    image: co.Map<{
        original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema;
        originalSize: ZodTuple<[ZodNumber, ZodNumber], null>;
        placeholderDataURL: ZodOptional<ZodString>;
        progressive: ZodBoolean;
    }, co.FileStream, Group | Account>;
    thumbnail: co.Map<...>;
}, unknown, Group | Account>
ProductImage
.
CoMapSchema<{ image: CoMapSchema<{ original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema; originalSize: ZodTuple<[ZodNumber, ZodNumber], null>; placeholderDataURL: ZodOptional<ZodString>; progressive: ZodBoolean; }, FileStreamSchema, Group | Account>; thumbnail: CoMapSchema<...>; }, unknown, Group | Account>.create(init: {
    image: ({
        readonly original: FileStream | null;
        readonly originalSize: [number, number];
        readonly placeholderDataURL: string | undefined;
        readonly progressive: boolean;
    } & {
        ...;
    } & CoMap) | {
        ...;
    };
    thumbnail: ({
        readonly original: FileStream | null;
        readonly originalSize: [number, number];
        readonly placeholderDataURL: string | undefined;
        readonly progressive: boolean;
    } & ... 1 more ... & CoMap) | {
        ...;
    };
}, options?: {
    owner?: Group;
    unique?: CoValueUniqueness["uniqueness"];
} | Group): {
    ...;
} & CoMap (+1 overload)
create
({
image: ({
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & {
    ...;
} & CoMap) | {
    ...;
}
image
:
const mainImage: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & {
    ...;
} & CoMap, {
    ...;
}, 10, []>
mainImage
,
thumbnail: ({
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & {
    ...;
} & CoMap) | {
    ...;
}
thumbnail
,
});

Creating images on the server

We provide a createImage function to create images from server side using the same options as the browser version, using the package jazz-tools/media/server. Check the server worker documentation to learn more.

The resize features are based on the sharp library, then it is requested as peer dependency in order to use it.

No content available for tab:
import fs from "node:fs";
import { createImage } from "jazz-tools/media/server";

const image = fs.readFileSync(new URL("./image.jpg", import.meta.url));

await createImage(image, {
  // options
});

Displaying Images

Like other CoValues, ImageDefinition can be used to load the object.

import { 
type ImageDefinition = {
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & {
    ...;
} & CoMap
const ImageDefinition: CoMapSchema<{
    original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema;
    originalSize: ZodTuple<[ZodNumber, ZodNumber], null>;
    placeholderDataURL: ZodOptional<ZodString>;
    progressive: ZodBoolean;
}, FileStreamSchema, Group | Account>
@categoryMedia
ImageDefinition
} from "jazz-tools";
const
const image: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & CoMap, {
    ...;
}, 10, []> | null
image
= await
const ImageDefinition: CoMapSchema<{
    original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema;
    originalSize: ZodTuple<[ZodNumber, ZodNumber], null>;
    placeholderDataURL: ZodOptional<ZodString>;
    progressive: ZodBoolean;
}, FileStreamSchema, Group | Account>
@categoryMedia
ImageDefinition
.
CoMapSchema<{ original: import("/vercel/path0/packages/jazz-tools/dist/tools/internal").FileStreamSchema; originalSize: ZodTuple<[ZodNumber, ZodNumber], null>; placeholderDataURL: ZodOptional<ZodString>; progressive: ZodBoolean; }, FileStreamSchema, Group | Account>.load<{
    original: true;
}>(id: string, options?: {
    resolve?: RefsToResolve<{
        readonly original: FileStream | null;
        readonly originalSize: [number, number];
        readonly placeholderDataURL: string | undefined;
        readonly progressive: boolean;
    } & CoMap, 10, []> | undefined;
    loadAs?: Account | AnonymousJazzAgent;
    skipRetry?: boolean;
    unstable_branch?: BranchDefinition;
} | undefined): Promise<...>
load
("123", {
resolve?: RefsToResolve<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & CoMap, 10, []> | undefined
resolve
: {
original?: RefsToResolve<FileStream, 10, [0]> | undefinedoriginal: true, }, }); if(
const image: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & CoMap, {
    ...;
}, 10, []> | null
image
) {
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
({
originalSize: [number, number]originalSize:
const image: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & CoMap, {
    ...;
}, 10, []>
image
.originalSize: [number, number]originalSize,
placeholderDataUrl: string | undefinedplaceholderDataUrl:
const image: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & CoMap, {
    ...;
}, 10, []>
image
.placeholderDataURL: string | undefinedplaceholderDataURL,
original: FileStreamoriginal:
const image: CoMapLikeLoaded<{
    readonly original: FileStream | null;
    readonly originalSize: [number, number];
    readonly placeholderDataURL: string | undefined;
    readonly progressive: boolean;
} & CoMap, {
    ...;
}, 10, []>
image
.original: FileStreamoriginal, // this FileStream may be not loaded yet
}); }

image.original is a FileStream and its content can be read as described in the FileStream documentation.

Since FileStream objects are also CoValues, they must be loaded before use. To simplify loading, if you want to load the binary data saved as Original, you can use the loadImage function.

import { 
function loadImage(imageOrId: ImageDefinition | string): Promise<{
    width: number;
    height: number;
    image: FileStream;
} | null>
loadImage
} from "jazz-tools/media";
const
const image: {
    width: number;
    height: number;
    image: FileStream;
} | null
image
= await
function loadImage(imageOrId: ImageDefinition | string): Promise<{
    width: number;
    height: number;
    image: FileStream;
} | null>
loadImage
(const imageDefinitionOrId: stringimageDefinitionOrId);
if(
const image: {
    width: number;
    height: number;
    image: FileStream;
} | null
image
=== null) {
throw new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
("Image not found");
} const const img: HTMLImageElementimg = var document: Document
[MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/document)
document
.Document.createElement<"img">(tagName: "img", options?: ElementCreationOptions): HTMLImageElement (+2 overloads)
Creates an instance of the element for the specified tag.
@paramtagName The name of an element. [MDN Reference](https://developer.mozilla.org/docs/Web/API/Document/createElement)
createElement
("img");
const img: HTMLImageElementimg.HTMLImageElement.width: number
Sets or retrieves the width of the object. [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/width)
width
=
const image: {
    width: number;
    height: number;
    image: FileStream;
}
image
.width: numberwidth;
const img: HTMLImageElementimg.HTMLImageElement.height: number
Sets or retrieves the height of the object. [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/height)
height
=
const image: {
    width: number;
    height: number;
    image: FileStream;
}
image
.height: numberheight;
const img: HTMLImageElementimg.HTMLImageElement.src: string
The address or URL of the a media resource that is to be considered. [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/src)
src
=
var URL: {
    new (url: string | URL, base?: string | URL): URL;
    prototype: URL;
    canParse(url: string | URL, base?: string | URL): boolean;
    createObjectURL(obj: Blob | MediaSource): string;
    parse(url: string | URL, base?: string | URL): URL | null;
    revokeObjectURL(url: string): void;
}
The URL interface represents an object providing static methods used for creating object URLs. [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) `URL` class is a global reference for `import { URL } from 'node:url'` https://nodejs.org/api/url.html#the-whatwg-url-api
@sincev10.0.0
URL
.function createObjectURL(obj: Blob | MediaSource): string
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static)
createObjectURL
(
const image: {
    width: number;
    height: number;
    image: FileStream;
}
image
.image: FileStreamimage.
FileStream.toBlob(options?: {
    allowUnfinished?: boolean;
}): Blob | undefined
toBlob
()!);
const img: HTMLImageElementimg.GlobalEventHandlers.onload: ((this: GlobalEventHandlers, ev: Event) => any) | null
Fires immediately after the browser loads the object.
@paramev The event. [MDN Reference](https://developer.mozilla.org/docs/Web/API/SVGElement/load_event)
onload
= () =>
var URL: {
    new (url: string | URL, base?: string | URL): URL;
    prototype: URL;
    canParse(url: string | URL, base?: string | URL): boolean;
    createObjectURL(obj: Blob | MediaSource): string;
    parse(url: string | URL, base?: string | URL): URL | null;
    revokeObjectURL(url: string): void;
}
The URL interface represents an object providing static methods used for creating object URLs. [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) `URL` class is a global reference for `import { URL } from 'node:url'` https://nodejs.org/api/url.html#the-whatwg-url-api
@sincev10.0.0
URL
.function revokeObjectURL(url: string): void
[MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static)
revokeObjectURL
(const img: HTMLImageElementimg.HTMLImageElement.src: string
The address or URL of the a media resource that is to be considered. [MDN Reference](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/src)
src
);

If the image was generated with progressive loading, and you want to access the best-fit resolution, use loadImageBySize. It will load the image of the best resolution that fits the wanted width and height.

import { 
function loadImageBySize(imageOrId: ImageDefinition | string, wantedWidth: number, wantedHeight: number): Promise<{
    width: number;
    height: number;
    image: FileStream;
} | null>
loadImageBySize
} from "jazz-tools/media";
const
const image: {
    width: number;
    height: number;
    image: FileStream;
} | null
image
= await
function loadImageBySize(imageOrId: ImageDefinition | string, wantedWidth: number, wantedHeight: number): Promise<{
    width: number;
    height: number;
    image: FileStream;
} | null>
loadImageBySize
(const imageDefinitionOrId: stringimageDefinitionOrId, 600, 600); // 600x600
if(
const image: {
    width: number;
    height: number;
    image: FileStream;
} | null
image
) {
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+2 overloads)
[MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
({
width: numberwidth:
const image: {
    width: number;
    height: number;
    image: FileStream;
}
image
.width: numberwidth,
height: numberheight:
const image: {
    width: number;
    height: number;
    image: FileStream;
}
image
.height: numberheight,
image: FileStreamimage:
const image: {
    width: number;
    height: number;
    image: FileStream;
}
image
.image: FileStreamimage,
}); }

If want to dynamically listen to the loaded resolution that best fits the wanted width and height, you can use the subscribe and the highestResAvailable function.

import { ImageDefinition } from "jazz-tools";
// function highestResAvailable(image: ImageDefinition, wantedWidth: number, wantedHeight: number): FileStream | null
import { highestResAvailable } from "jazz-tools/media";

const image = await ImageDefinition.load(imageId);

if(image === null) {
  throw new Error("Image not found");
}

const img = document.createElement("img");
img.width = 600;
img.height = 600;

// start with the placeholder
if(image.placeholderDataURL) {
  img.src = image.placeholderDataURL;
}

// then listen to the image changes
image.$jazz.subscribe({}, (image) => {
  const bestImage = highestResAvailable(image, 600, 600);

  if(bestImage) {
    // bestImage is again a FileStream
    const blob = bestImage.image.toBlob();
    if(blob) {
      const url = URL.createObjectURL(blob);
      img.src = url;
      img.onload = () => URL.revokeObjectURL(url);
    }
  }
});

Custom image manipulation implementations

To manipulate images (like placeholders, resizing, etc.), createImage() uses different implementations depending on the environment.

If you want to use a custom implementation, you can use the createImageFactory function in order create your own createImage function and use your preferred image manipulation library.

import { createImageFactory } from "jazz-tools/media";

const createImage = createImageFactory({
    createFileStreamFromSource: async (source, owner) => {
        // ...
    },
    getImageSize: async (image) => {
        // ...
    },
    getPlaceholderBase64: async (image) => {
        // ...
    },
    resize: async (image, width, height) => {
        // ...
    },
});

Best Practices

  • Set image sizes when possible to avoid layout shifts
  • Use placeholders (like LQIP - Low Quality Image Placeholders) for instant rendering
  • Prioritize loading the resolution appropriate for the current viewport
  • Consider device pixel ratio (window.devicePixelRatio) for high-DPI displays
  • Always call URL.revokeObjectURL after the image loads to prevent memory leaks