Skip to content

Utilities

Image

Bit.BlazorUI

BitImage is an img inside a frame, and nearly everything it offers is about the relationship between the two. The frame takes the size (Width, Height, AspectRatio, MaximizeFrame) and the shape (Rounded, Circular, Bordered) and clips what falls outside it, while ImageFit and ImagePosition decide what the image does inside it when the two are different shapes. The other half is what happens before the image is there: the component follows the browser's load and error events, hides the image until it has arrived, fades it in, holds the frame with a blurred placeholder or a loading template, and tries a fallback source before it gives up. What the browser itself decides stays the browser's: lazy loading, decoding, fetch priority and the srcset/sizes responsive picture are all reachable as parameters.

Usage

Every example is live. Open its code to see exactly what produced the component running underneath.

Basic

An image needs a Src and an Alt: the source is the file, and the alternate text is what the image says to anyone who cannot see it. The attribute is always rendered, so an image given no text at all is announced as decorative rather than read out as a file name - which means a decorative image is one whose Alt is deliberately left empty, not one that forgot it. With nothing else set, the frame takes the natural size of the image, and the image stays hidden until it has loaded. Title is the tooltip a mouse gets on hover - an aside rather than a place for anything the image cannot do without, since a touch screen never shows it.

A disabled image keeps its colors and dims, and stops answering the pointer.
The bit platform logo

Disabled
The bit platform logo

Width & Height

Width and Height size the frame. A bare number is read as a pixel count and anything else is used as written, so any CSS length works - 9rem, 50%, calc(100vw - 2rem). Given only one of the two, the image scales along the other one and keeps its aspect ratio; given both, the frame is exactly that size and the image is left to overflow it unless an ImageFit says what to do instead. The backgrounds below are there to show the frame itself.
Width
The bit platform logo

Height
The bit platform logo

Width & Height
The bit platform logo

AspectRatio

AspectRatio gives the frame a shape instead of a second measurement: a width and a ratio are enough, and the height follows. It is what reserves the room the image will need before it has arrived, so the content below it is not pushed down the moment it does - the layout shift a page is measured by. It pairs with ImageFit, which decides what the image does inside a frame whose shape is not its own.
16/9
A landscape photograph
1/1
A landscape photograph
3/4
A landscape photograph

ImageFit

ImageFit settles what happens once the image and the frame turn out to be different shapes. None leaves both alone and crops whatever does not fit from the right and the bottom; Center does the same but crops around the middle. Contain fits all of the image inside the frame and leaves the rest of the frame empty, Cover fills the frame and crops the overflow, Fill stretches the image to the frame exactly and distorts it, and ScaleDown is Contain that never enlarges a small image. CenterContain and CenterCover are the two centered variants that scale along the one axis Cover (the parameter) names.
None
The bit platform logo

Center
The bit platform logo

Contain
The bit platform logo

Cover
The bit platform logo

Fill
The bit platform logo

ScaleDown
The bit platform logo

CenterContain
The bit platform logo

CenterCover
The bit platform logo

ImagePosition

A fit that crops has to crop somewhere, and by default that is around the middle of the image - which is the wrong half of a photograph whose subject is not there. ImagePosition is the CSS object-position of the image: a keyword pair (top, bottom right) or two lengths or percentages. It only has an effect where something is actually cropped, so it goes with Cover and with a frame narrower or shorter than the image.
top
A landscape photograph cropped to its top edge
center (default)
A landscape photograph cropped around its middle
bottom
A landscape photograph cropped to its bottom edge

Cover

Cover is read by the two centered fits alone, and it names the axis they scale along. It describes the shape of the frame rather than of the image: Landscape for a wide frame, where the image is shown at the full height and the width follows, and Portrait - the default - for a tall one, where it is the width that is filled. The other fits are expressed with object-fit, which reads both shapes on its own and needs no such hint.
ImageFit: CenterCover
Landscape
The bit platform logo
Portrait
The bit platform logo

ImageFit: CenterContain
Landscape
The bit platform logo
Portrait
The bit platform logo

MaximizeFrame

MaximizeFrame hands the sizing over to whatever is around the component: the frame takes the full width and height of its parent, and the image covers it. An explicit ImageFit still has the last word over that cover, so the same maximized frame can just as well contain the image instead of cropping it.
A landscape photograph
A landscape photograph

Shape & shadow

The frame is what carries the shape, and it clips - so Rounded and Circular crop the image rather than merely rounding a box drawn around it. Rounded takes the theme's surface radius, which makes it follow the design system rather than a number written here; Circular is only a circle while the frame is a square, so it goes with an AspectRatio of 1 and a Cover fit. Bordered draws the theme's border around it, inside the frame's own size, and Shadow lifts it off the surface with the same elevation every other raised surface of the library has. All four read the theme, so they follow a design system rather than a number written on the page.
A landscape photograph in a rounded frame
A landscape photograph in a circular frame
A landscape photograph in a bordered, rounded frame
A landscape photograph in a raised, rounded frame

Loading & error states

The component follows the browser's own load and error events, and the resulting BitImageState decides what is on screen: LoadingTemplate stands in the frame while the image is on its way and ErrorTemplate once it has failed, and OnLoadingStateChange reports every transition - including the return to Loading when the source changes. LoadingState is the same value read off the component, and ReloadAsync asks for the image again from the beginning, which is the answer to a failure that was the network's rather than the image's: it replaces the img element instead of patching it, so the browser really does fetch a source it already holds an answer for.
State: Loading


FallbackSrc

FallbackSrc is the other answer to a failure: instead of a template, another image. It is tried exactly once - a fallback that fails as well leaves the component in the error state rather than asking for it again - and it is also what is shown when no Src is given at all, which makes a missing avatar and a broken one look the same. A fallback belongs to the page rather than to the network: something already cached or inlined as a data URI, since whatever kept the first image away may well keep this one away too.
A source that does not exist, answered by the fallback
The bit platform logo, shown in place of a missing image

No source at all, answered by the same fallback
The bit platform logo, shown in place of a missing image

PlaceholderSrc

PlaceholderSrc is the blur-up placeholder: a tiny, heavily compressed stand-in - normally the same picture at a few dozen pixels, inlined as a data URI so it costs no request - which fills the frame from the first frame and is taken away the moment the real image arrives. It fills the frame, so it needs a frame with a size: a Width and a Height, an AspectRatio, or a MaximizeFrame. Paired with FadeIn it is the whole of the progressive-image effect, with no layout shift at either end.

FadeIn & StartVisible

The image is hidden until it has loaded, which keeps a half-drawn or broken one off the page at the cost of the frame collapsing while it waits. StartVisible is the other trade: the image is shown from the start - the browser's own progressive rendering - and hidden only if it fails. FadeIn animates the moment the image becomes visible rather than the mounting of the component, so it is the arrival that is animated; it collapses to nothing under prefers-reduced-motion unless ForceAnimation says otherwise.

FadeIn
An image served with a delay

StartVisible
An image served with a delay

Native loading attributes

What the browser decides for itself stays the browser's. Loading is the loading attribute: a Lazy image is only fetched once the browser expects it to be needed, so it keeps the room it will take up while it waits - give it a Height or an AspectRatio so that room is the right size - and it is never right for what is already on the first screen. FetchPriority reorders one image against everything else being fetched, which is worth setting on exactly two kinds: the largest thing on the first screen, and the decorative ones far below that should not compete with it. Decoding hints at whether the pixels may be produced off the critical path. CrossOrigin and ReferrerPolicy cover the two things a cross-origin image needs to settle - whether its pixels may be read back, and how much of the current address is handed to whoever serves it - and anything else an img accepts goes through ImageAttributes, which is merged with what the parameters set rather than replaced by it.
A landscape photograph

A landscape photograph

Srcset & Sizes

Srcset hands the browser a list of the same picture at different sizes, each tagged with its width (480w) or its pixel density (2x), and lets it choose - a decision the page cannot make, since only the browser knows the screen and the network. Sizes is what makes a width-descriptor list usable: it says how wide the image will be laid out before the layout is known, and without it the browser assumes the full width of the viewport and over-fetches accordingly. Src stays as the answer for anything that reads neither.
A landscape photograph served at the size the viewport needs

Sources

Srcset answers "how many pixels"; Sources answers the two questions it cannot. The first is art direction - a different crop of the subject at a different viewport, a wide hero on a desktop and a square one on a phone - which is a decision about the composition rather than about the file size. The second is format: an AVIF and a WebP offered ahead of the JPEG that every browser understands, each with its Type, so a browser that cannot read one skips it without fetching anything. The browser walks the list in order and takes the first it is satisfied by, which makes the order the priority, and Src stays the answer that is always understood. The image is wrapped in a picture that lays nothing out of its own, so the frame, the fit and the shape are untouched.
Resize the window across 600px to swap the crop
A landscape photograph, cropped differently on a narrow viewport

OnClick

Assigning OnClick makes the image a button rather than a picture: it becomes focusable, is announced as a button whose name is the Alt - so the text says what the click does rather than what the image shows - and answers the Enter and the Space keys as well as the pointer. A disabled image answers neither. Draggable is worth setting to false on a clickable image, since a browser makes an image draggable of itself and a press that was meant as a click can start a drag instead.
Count this click
This one is disabled
Clicked 0 times

ChildContent

ChildContent is a layer over the image, filling the frame: a caption, a badge, a gradient scrim, a play button. It is laid over the whole frame, so it needs a frame with a size, and it is the last thing in it, which is what puts it above the image without either of them needing a z-index.
A landscape photograph
A caption laid over the image

Style & Class

Style and Class reach the frame, which is the element that carries the size and the shape, and Styles and Classes reach each part of the component by name - the Root frame, the Image itself, the Placeholder, the two template wrappers and the Content overlay. A filter, a mask or a transition belongs on the image; a shadow or a margin belongs on the frame.
Component's Style & Class:
Styled
The bit platform logo

Classed
The bit platform logo


Styles & Classes:
Styles
The bit platform logo

Classes
The bit platform logo

RTL

An image has no reading direction of its own - it is a picture, not a run of text - so Dir changes nothing about how it is drawn. What it does change is the direction the content of the component flows in: a caption laid over the image, a loading or error template, and the placement of the frame within whatever lays it out. The direction is also cascaded, so a BitImage inside an RTL container inherits it.
عکسی از یک منظره
نوشته‌ای روی تصویر

API

Every parameter, public member, sub-class and enum this component exposes.

BitImage parameters

Name Type Default value Description
Alt string? null Specifies an alternate text for the image. The attribute is always rendered, so an image given no text is announced as decorative (alt="") rather than read out as a file name.
AspectRatio string? null The aspect ratio of the frame of the image, as a CSS aspect-ratio value (e.g. "16/9" or "1"). Reserves the room the image will need before it arrives.
Bordered bool false Renders a border around the frame of the image.
ChildContent RenderFragment? null The content rendered over the image, filling the frame.
Circular bool false Renders the frame of the image as a circle. Takes precedence over Rounded.
Classes BitImageClassStyles? null Custom CSS classes for different parts of the BitImage.
Cover BitImageCover? null Specifies the cover style to be used for this image. Only the CenterCover and CenterContain fits read it.
CrossOrigin BitImageCrossOrigin? null Specifies the CORS setting the image is requested with.
Decoding BitImageDecoding? null Hints the browser at whether the image may be decoded asynchronously.
Draggable bool? null Specifies whether the image can be dragged by the user.
ErrorTemplate RenderFragment? null The custom template used to show the error state of the image.
FadeIn bool false If true, fades the image in when it becomes visible.
FallbackSrc string? null The source of the image to show when the one given by Src fails to load, or when no Src is given at all. It is tried exactly once.
FetchPriority BitImageFetchPriority? null Hints the browser at the priority this image is fetched with, relative to the other resources of the page.
Height string? null The image height value. A bare number is read as a pixel count; anything else is used as written.
ImageAttributes Dictionary<string, object> new Dictionary<string, object>() Capture and render additional attributes in addition to the image's parameters. The dictionary is merged with the attributes the component builds itself rather than replaced by them.
ImageFit BitImageFit? null Used to determine how the image is scaled and cropped to fit the frame.
ImagePosition string? null The position of the image inside its frame, as a CSS object-position value (e.g. "top", "50% 25%"). It decides which part of the image survives a crop.
Loading BitImageLoading? null Allows for browser-level image loading (lazy or eager).
LoadingTemplate RenderFragment? null The custom template used to show the loading state of the image.
MaximizeFrame bool false If true, the image frame will expand to fill its parent container.
OnClick EventCallback<MouseEventArgs> null Callback for when the image is clicked. Assigning it makes the image a focusable button that also answers the Enter and Space keys.
OnError EventCallback null Callback for when the image fails to load, including the failure that is answered by falling back to the FallbackSrc.
OnLoad EventCallback null Callback for when the image has been loaded successfully.
OnLoadingStateChange EventCallback<BitImageState> null Optional callback method for when the image load state has changed.
PlaceholderSrc string? null The source of a placeholder image shown, blurred, while the image itself is still loading.
ReferrerPolicy BitImageReferrerPolicy? null Specifies how much of the address of the current page is sent to whoever serves the image.
Rounded bool false Rounds the corners of the frame of the image.
Shadow bool false Renders a shadow under the frame of the image, lifting it off the surface it sits on.
Sizes string? null The value of the sizes attribute of the image, which tells the browser how wide the image will be laid out at before it knows the layout.
Sources IEnumerable<BitImageSource>? null The alternative sources of the image, offered to the browser ahead of Src. This is the art-direction and the format-negotiation half of responsive images, which Srcset cannot express.
Src string? null Specifies the src of the image. Changing it returns the component to the Loading state.
Srcset string? null The set of image sources the browser may choose from, with their width or density descriptors (e.g. "photo-480.jpg 480w, photo-960.jpg 960w").
StartVisible bool false If true, the image starts as visible and is hidden on error. Otherwise, the image is hidden until it is successfully loaded.
Styles BitImageClassStyles? null Custom CSS styles for different parts of the BitImage.
Title string? null The title to show when the mouse is placed on the image.
Width string? null The image width value. A bare number is read as a pixel count; anything else is used as written.

BitImage public members

Name Type Default value Description
FocusAsync ValueTask Gives the browser focus to the img element of the component. Only a clickable image (one with an OnClick) or one given an explicit TabIndex is focusable at all, so anywhere else the call does nothing.
ImageElement ElementReference The reference to the img element of the component, for whatever has to reach the picture itself rather than the frame around it. RootElement is that frame.
LoadingState BitImageState BitImageState.Loading The current loading state of the image.
ReloadAsync Task Requests the image again from the beginning, whichever state it is in: the component returns to the Loading state, forgets that a FallbackSrc has been tried, and replaces the img element rather than patching it - which is what makes the browser fetch a source it already holds an answer for.

BitComponentBase parameters

Name Type Default value Description
AriaLabel string? null Gets or sets the accessible label for the component, used by assistive technologies.
Class string? null Gets or sets the CSS class name(s) to apply to the rendered element.
Dir BitDir? null Gets or sets the text directionality for the component's content.
ForceAnimation bool false Gets or sets a value indicating whether the component's animations play at their full duration even when reduced motion is requested.
HtmlAttributes Dictionary<string, object> new Dictionary<string, object>() Captures additional HTML attributes to be applied to the rendered element, in addition to the component's parameters.
Id string? null Gets or sets the unique identifier for the component's root element.
IsEnabled bool true Gets or sets a value indicating whether the component is enabled and can respond to user interaction.
Style string? null Gets or sets the CSS style string to apply to the rendered element.
TabIndex string? null Gets or sets the tab order index for the component when navigating with the keyboard.
Visibility BitVisibility BitVisibility.Visible Gets or sets the visibility state (visible, hidden, or collapsed) of the component.

BitComponentBase public members

Name Type Default value Description
UniqueId Guid Guid.NewGuid() Gets the readonly unique identifier for the component's root element, assigned when the component instance is constructed.
RootElement ElementReference Gets the reference to the root HTML element associated with this component.

BitImageClassStyles properties

Name Type Default value Description
Root string? null Custom CSS classes/styles for the root element of the image.
Placeholder string? null Custom CSS classes/styles for the placeholder image element, which is only rendered while a PlaceholderSrc is provided and the image itself has not loaded yet.
Image string? null Custom CSS classes/styles for the image element.
LoadingTemplate string? null Custom CSS classes/styles for the element wrapping the LoadingTemplate of the image.
ErrorTemplate string? null Custom CSS classes/styles for the element wrapping the ErrorTemplate of the image.
Content string? null Custom CSS classes/styles for the overlay element that holds the ChildContent of the image.

BitImageSource properties

One alternative source of the image, rendered as a source element of the picture the image is then wrapped in. The browser walks the sources in order and takes the first one whose Media and Type it is satisfied by.

Name Type Default value Description
Srcset string? null The set of images this source offers, with their width or density descriptors (e.g. "photo-480.avif 480w, photo-960.avif 960w"). This is the only required member.
Media string? null The media query the source applies to (e.g. "(max-width: 600px)"). A source with none applies whatever the viewport is, so it belongs last among the sources that carry one.
Sizes string? null How wide the image will be laid out at, for the browser to choose among a width-descriptor Srcset with.
Type string? null The MIME type of the images this source offers (e.g. "image/avif"). A browser that cannot read the type skips the source without fetching anything.
Width int? null The intrinsic width, in pixels, of the images this source offers.
Height int? null The intrinsic height, in pixels, of the images this source offers.

BitImageFit enum

Name Value Description
None 0 Neither the image nor the frame are scaled. The image keeps its natural size and whatever of it does not fit the frame is cropped away from the right and the bottom.
Center 1 The image is not scaled. The image is centered and cropped within the content box.
CenterContain 2 The image will be centered horizontally and vertically within the frame and maintains its aspect ratio, scaled down where needed so that all of it fits inside the frame.
CenterCover 3 The image will be centered horizontally and vertically within the frame and maintains its aspect ratio, scaled up where needed so that it covers the frame and the overflow is cropped.
Contain 4 The image is scaled to maintain its aspect ratio while being fully contained within the frame.
Cover 5 The image is scaled to maintain its aspect ratio while filling the frame.
Fill 6 The image is stretched to fill the frame exactly, without maintaining its aspect ratio.
ScaleDown 7 The image is contained within the frame, but never scaled up: an image smaller than the frame keeps its natural size.

BitImageCover enum

Name Value Description
Landscape 0 The image will be shown at 100% height of container and the width will be scaled accordingly.
Portrait 1 The image will be shown at 100% width of container and the height will be scaled accordingly.

BitImageState enum

Name Value Description
Loading 0 The image is loading from its source.
Loaded 1 The image has been loaded successfully.
Error 2 An error has been encountered while loading the image. Where a FallbackSrc is provided, this state is only reached once that one has failed as well.

BitImageLoading enum

Name Value Description
Eager 0 The default behavior, eager tells the browser to load the image as soon as the img element is processed.
Lazy 1 Tells the user agent to hold off on loading the image until the browser estimates that it will be needed imminently.

BitImageDecoding enum

Name Value Description
Auto 0 The default behavior, which leaves the decision to the browser.
Sync 1 Decodes the image synchronously, so it is presented together with the rest of the content rendered in the same frame.
Async 2 Decodes the image asynchronously, so the rest of the content is not held back while the decoding runs.

BitImageFetchPriority enum

Name Value Description
Auto 0 The default behavior, which leaves the priority to the browser's own heuristics.
High 1 Fetches the image ahead of the other images of the page, for the one that is the page's largest contentful paint.
Low 2 Fetches the image after the other images of the page, for the ones that carry no meaning on the first screen.

BitImageCrossOrigin enum

Name Value Description
Anonymous 0 Sends a cross-origin request with no credentials: no cookie, no client certificate and no HTTP authentication.
UseCredentials 1 Sends a cross-origin request with credentials. The other origin has to answer with the matching Access-Control-Allow-Credentials header.

BitImageReferrerPolicy enum

Name Value Description
NoReferrer 0 Sends no Referer header at all.
NoReferrerWhenDowngrade 1 Sends the full URL, except to a less secure destination (HTTPS to HTTP), where nothing is sent.
Origin 2 Sends only the origin - the scheme, the host and the port - of the current page.
OriginWhenCrossOrigin 3 Sends the full URL to the same origin, and only the origin to any other one.
SameOrigin 4 Sends the full URL to the same origin, and nothing at all to any other one.
StrictOrigin 5 Sends only the origin, and nothing to a less secure destination (HTTPS to HTTP).
StrictOriginWhenCrossOrigin 6 The default behavior: the full URL to the same origin, the origin alone to another secure one, and nothing to a less secure destination.
UnsafeUrl 7 Sends the full URL to every destination, secure or not.

BitVisibility enum

Name Value Description
Visible 0 The content of the component is visible.
Hidden 1 The content of the component is hidden, but the space it takes on the page remains (visibility:hidden).
Collapsed 2 The component is hidden (display:none).

BitDir enum

Name Value Description
Ltr 0 Ltr (left to right) is to be used for languages that are written from the left to the right (like English).
Rtl 1 Rtl (right to left) is to be used for languages that are written from the right to the left (like Arabic).
Auto 2 Auto lets the user agent decide. It uses a basic algorithm as it parses the characters inside the element until it finds a character with a strong directionality, then applies that directionality to the whole element.

Feedback

Found a mistake, a gap, or something that could be clearer? Every page and every component is one click from its source.