---
title: Let editors select image variants
---

> **Documentation indexes**
> The indexes below list current page URLs with titles and descriptions. Links on this page point to the Markdown versions of the linked pages.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

When you render images in page templates or views, you choose the image variant in code. Your business needs may also require editors to choose the image variant themselves in a Page Builder widget. For these cases, you can implement an **Image size** setting that lets editors choose the right format for each placement on the page.

By the end of this material, you'll build a drop-down options provider that lists the _Smart crop_ image variants with their dimensions, pair it with a _Responsive_ / _Fixed variant_ switch and an asset selector in an _Image_ widget, and render the result using a responsive image tag helper.

The finished showcase page has two _Image_ widgets with the same photo. An editor set the first to _Responsive_ and the second to _Fixed variant_ with the _Card 4:3_ variant.

![The image variants showcase page at a 1440 px wide viewport with two Image widgets and the same photo of farfalle with pesto. The first, set to Responsive, fills the width of its section, and the browser picks ScaleW1600 from its srcset. The second, set to Fixed variant with Card 4:3, shows the Card800x600 variant, a fixed 800 × 600 px crop.](https://docs.kentico.com/docsassets/guides/let-editors-choose-image-variants/Image_Widgets_1440.jpg "Two Image widgets at a 1440 px viewport")

## Before you start

This material closes a three-part series that starts with [Plan your image variant set](https://docs.kentico.com/guides/development/image-variants/plan-your-image-variant-set.md) and continues in [Render image variants in views and components](https://docs.kentico.com/guides/development/image-variants/render-image-variants-in-views.md). Make sure you have the following:

- Image variant definitions configured in your instance and a responsive image tag helper that accepts a variant code name, such as `tg-responsive-image` from the _Training guides_ repository.
- Familiarity with [Page Builder widgets](https://docs.kentico.com/documentation/developers-and-admins/development/builders/page-builder/widgets-for-page-builder.md), [widget properties](https://docs.kentico.com/documentation/developers-and-admins/development/builders/page-builder/widgets-for-page-builder/widget-properties.md) and [drop-down option providers](https://docs.kentico.com/guides/development/page-builder/map-enum-to-dropdown.md).
- A running instance of Xperience by Kentico, preferably [31.7.2](https://docs.kentico.com/changelog.md) or higher.

  > **Note:** Some features covered in the Training guides may not work in older versions.

> **Info:** **Code samples**
>
> You can find a project with completed, working versions of code samples from this guide and others in the [finished branch](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished) of the _Training guides_ repository.
>
> The [main branch](https://github.com/Kentico/xperience-by-kentico-training-guides) of the repository provides a starting point to code along with the guides.
>
> The code samples in this guide come from a project that targets [.NET 10](https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10/overview) and uses [implicit using directives](https://learn.microsoft.com/en-us/dotnet/core/project-sdk/overview#implicit-using-directives). You may need to add additional `using` directives to your code if your project does not use this feature.

## Explore the Image widget

In the _Training guides_ repository, the _Image_ widget lets editors select an image asset and its size in the widget properties dialog. In _Responsive_ mode, the `tg-responsive-image` tag helper outputs the full responsive width series. In _Fixed variant_ mode, the widget passes the selected variant to the tag helper, which outputs that single variant file.

On the _Image variants_ demonstration page under _News and articles_, the first section of the template's editable area contains two _Image_ widgets configured with the same photo:

- One uses _Responsive_ to output the responsive width series.
- The other uses _Fixed variant_ with the _Card 4:3_ variant to output a fixed 800 × 600 px crop.

You can find the widget implementation in the _finished_ branch under [`Features/ResponsiveImages/Widgets/ImageWidget`](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished/src/TrainingGuides.Web/Features/ResponsiveImages/Widgets/ImageWidget) in the `TrainingGuides.Web` project, and the drop-down options provider in [`Features/ResponsiveImages/OptionProviders`](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished/src/TrainingGuides.Web/Features/ResponsiveImages/OptionProviders).

## List the Smart crop variants in a drop-down

To populate the **Variant** drop-down dynamically, implement `IDropDownOptionsProvider`. Xperience instantiates the provider through dependency injection, which lets the constructor accept `IInfoProvider<StandardMediaDimensionsInfo>` directly. Because the drop-down queries the provider each time an editor opens the widget properties dialog, newly created variant definitions appear automatically.

In the _Training guides_ repository, `ImageVariantOptionsProvider` builds the option list as follows:

- **Smart crops only:** _Scaled_ definitions make up the responsive width series that the tag helper outputs in _Responsive_ mode.
- **Code names as values:** each variant definition becomes an option whose `Value` is the definition's code name.
- **Dimensions in labels:** each option's `Text` combines the display name and pixel dimensions, such as _Card 4:3 (800 × 600 px)_.
- **Sorting:** options are ordered by width and then height.

```csharp title="ImageVariantOptionsProvider.cs"
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using CMS.ContentEngine;
using CMS.DataEngine;

using Kentico.Xperience.Admin.Base.FormAnnotations;

namespace TrainingGuides.Web.Features.ResponsiveImages.OptionProviders;

/// <summary>
/// Populates a drop-down with the Smart crop image variant definitions.
/// </summary>
/// <param name="standardMediaDimensionsInfoProvider">
/// Provider used to query image variant definitions.
/// </param>
public class ImageVariantOptionsProvider(
    IInfoProvider<StandardMediaDimensionsInfo> standardMediaDimensionsInfoProvider)
    : IDropDownOptionsProvider
{
    /// <inheritdoc/>
    public async Task<IEnumerable<DropDownOptionItem>> GetOptionItems()
    {
        var definitions = await standardMediaDimensionsInfoProvider.Get()
            .GetEnumerableTypedResultAsync();

        return BuildOptionItems(definitions.Select(definition => new VariantDefinition(
            definition.StandardMediaDimensionsName,
            definition.StandardMediaDimensionsDisplayName,
            definition.StandardMediaDimensionsWidth,
            definition.StandardMediaDimensionsHeight,
            definition.StandardMediaDimensionsTransformationType)));
    }

    /// <summary>
    /// Selects available Smart crop definitions.
    /// </summary>
    /// <param name="definitions">The image variant definitions to format.</param>
    /// <returns>Drop-down options with variant code names as values.</returns>
    internal static IEnumerable<DropDownOptionItem> BuildOptionItems(
        IEnumerable<VariantDefinition> definitions) =>
        definitions
            .Where(definition => definition.TransformationType == MediaTransformationType.SmartCrop)
            .OrderBy(definition => definition.Width)
            .ThenBy(definition => definition.Height)
            .Select(definition => new DropDownOptionItem
            {
                Value = definition.CodeName,
                Text = $"{definition.DisplayName} ({definition.Width} × {definition.Height} px)"
            });

    /// <summary>
    /// Stores available configuration options.
    /// </summary>
    /// <param name="CodeName">The definition's code name, used as the option value.</param>
    /// <param name="DisplayName">The definition's display name.</param>
    /// <param name="Width">Width in pixels.</param>
    /// <param name="Height">Height in pixels.</param>
    /// <param name="TransformationType">The variant transformation type.</param>
    internal record VariantDefinition(string CodeName, string DisplayName, int Width,
        int Height, MediaTransformationType TransformationType);
}
```

The following screenshot shows the widget's configuration dialog:

![The Image properties dialog of the Image widget with Fixed variant selected under Image size and the Variant drop-down open.](https://docs.kentico.com/docsassets/guides/let-editors-choose-image-variants/Image_Variant_Drop_Down.png "The Variant drop-down with every Smart crop option")

If a specific widget should only expose a subset of variants, create a dedicated `IDropDownOptionsProvider` class for that widget.

## Add the image size settings to the widget properties

`ImageWidgetProperties` pairs a content item selector restricted to a single item with two settings:

- **Image size:** a radio group with the _Responsive_ and _Fixed variant_ options. _Responsive_ is the default.
- **Variant:** a drop-down backed by `ImageVariantOptionsProvider`. The `VisibleIfEqualTo` attribute shows the drop-down only when _Fixed variant_ is selected.

```csharp title="ImageWidgetProperties.cs"
using System;
using System.Collections.Generic;

using CMS.ContentEngine;

using Kentico.PageBuilder.Web.Mvc;
using Kentico.Xperience.Admin.Base.FormAnnotations;

using TrainingGuides.Web.Features.ResponsiveImages.OptionProviders;

namespace TrainingGuides.Web.Features.ResponsiveImages.Widgets.ImageWidget;

/// <summary>
/// Configuration properties for the "Image" widget.
/// </summary>
public class ImageWidgetProperties : IWidgetProperties
{
    /// <summary>
    /// <see cref="SizeMode"/> value that renders the responsive width series.
    /// </summary>
    public const string RESPONSIVE = "responsive";

    /// <summary>
    /// <see cref="SizeMode"/> value that renders the variant in <see cref="ImageVariant"/>.
    /// </summary>
    public const string FIXED = "fixed";

    private const string RESPONSIVE_LABEL = "Responsive";
    private const string FIXED_LABEL = "Fixed variant";

    private const string SIZE_MODE_OPTIONS =
        $"{RESPONSIVE};{RESPONSIVE_LABEL}\n{FIXED};{FIXED_LABEL}";

    private const string SIZE_MODE_EXPLANATION = $"""
        <strong>{RESPONSIVE_LABEL}</strong>: automatically selects the most suitable variant.<br>
        <strong>{FIXED_LABEL}</strong>: selects a variant with fixed size. The variant can change the image's aspect ratio.
        """;

    /// <summary>
    /// Reference to the selected Asset content item.
    /// </summary>
    [ContentItemSelectorComponent(Asset.CONTENT_TYPE_NAME,
        Label = "Image", MaximumItems = 1, Order = 10)]
    public IEnumerable<ContentItemReference> Image { get; set; } = [];

    /// <summary>
    /// Whether the image adapts to the screen (<see cref="RESPONSIVE"/>) or renders the
    /// <see cref="ImageVariant"/> on every screen (<see cref="FIXED"/>).
    /// </summary>
    [RadioGroupComponent(Label = "Image size",
        Options = SIZE_MODE_OPTIONS,
        ExplanationText = SIZE_MODE_EXPLANATION,
        ExplanationTextAsHtml = true,
        Order = 20)]
    public string SizeMode { get; set; } = RESPONSIVE;

    /// <summary>
    /// Code name of the Smart crop variant rendered when <see cref="SizeMode"/> is
    /// <see cref="FIXED"/>. Ignored in <see cref="RESPONSIVE"/> mode.
    /// </summary>
    [DropDownComponent(Label = "Variant",
        DataProviderType = typeof(ImageVariantOptionsProvider),
        Placeholder = "Select a variant",
        ExplanationText = "An image that lacks the selected variant shows as responsive.",
        Order = 30)]
    [VisibleIfEqualTo(nameof(SizeMode), FIXED, StringComparison.OrdinalIgnoreCase)]
    public string? ImageVariant { get; set; }
}
```

A radio group's `Options` string puts each option on its own line and separates the stored value from its label with a semicolon. The labels are constants, so the explanation text, rendered as HTML through `ExplanationTextAsHtml`, always names the options the editor sees.

When an editor applies the properties dialog, Xperience validates the submitted variant against the provider's current option list and rejects any code name that is not in the list.

![The Image properties dialog of the Image widget with the Pasta asset in the Image selector, Fixed variant selected under Image size, and Card 4:3 (800 × 600 px) selected in the Variant drop-down. The explanation text under Image size reads: Responsive: automatically selects the most suitable variant. Fixed variant: selects a variant with fixed size. The variant can change the image's aspect ratio.](https://docs.kentico.com/docsassets/guides/let-editors-choose-image-variants/Image_Widget_Properties.png "Image properties dialog with the Pasta asset and the Card 4:3 variant")

## Render the selected variant

In `ImageWidgetViewComponent`, retrieve the selected _Asset_ item by its GUID, map it to an `ImageViewModel` alongside its alt text, and pass the selected variant code name to the widget view model when the editor selected _Fixed variant_. In _Responsive_ mode, the view component passes `null`, so a variant code name left in the properties never replaces the responsive width series. Because the image file is a field on the _Asset_ item itself, the retriever service's default linked-item depth is sufficient:

```csharp title="ImageWidgetViewComponent.cs"
using System;
using System.Linq;
using System.Threading.Tasks;

using Kentico.PageBuilder.Web.Mvc;

using Microsoft.AspNetCore.Mvc;

using TrainingGuides.Web.Features.ResponsiveImages.Models;
using TrainingGuides.Web.Features.ResponsiveImages.Widgets.ImageWidget;
using TrainingGuides.Web.Features.Shared.Services;

[assembly: RegisterWidget(
    identifier: ImageWidgetViewComponent.IDENTIFIER,
    viewComponentType: typeof(ImageWidgetViewComponent),
    name: "Image",
    propertiesType: typeof(ImageWidgetProperties),
    Description = "Displays an image as a responsive image or in a picked image variant.",
    IconClass = "icon-picture")]

namespace TrainingGuides.Web.Features.ResponsiveImages.Widgets.ImageWidget;

/// <summary>
/// Retrieves the selected image asset and passes it to the widget view with the chosen variant.
/// </summary>
/// <param name="contentItemRetrieverService">
/// Service used to retrieve the selected Asset content item.
/// </param>
public class ImageWidgetViewComponent(
    IContentItemRetrieverService contentItemRetrieverService) : ViewComponent
{
    /// <summary>
    /// Unique identifier for the "Image" widget.
    /// </summary>
    public const string IDENTIFIER = "TrainingGuides.ImageWidget";

    /// <summary>
    /// Loads the selected Asset content item and builds the widget view model.
    /// </summary>
    /// <param name="properties">The configured widget properties.</param>
    /// <returns>
    /// The widget view; the model is marked misconfigured when no valid image is selected.
    /// </returns>
    public async Task<IViewComponentResult> InvokeAsync(ImageWidgetProperties properties)
    {
        var assetGuid = properties.Image.Select(item => item.Identifier).FirstOrDefault();
        var asset = assetGuid == Guid.Empty
            ? null
            : await contentItemRetrieverService.RetrieveContentItemByGuid<Asset>(assetGuid);

        bool isFixed = string.Equals(properties.SizeMode, ImageWidgetProperties.FIXED,
            StringComparison.OrdinalIgnoreCase);

        var model = new ImageWidgetViewModel
        {
            Image = ImageViewModel.GetViewModel(asset),
            ImageVariant = isFixed ? properties.ImageVariant : null
        };

        return View("~/Features/ResponsiveImages/Widgets/ImageWidget/ImageWidget.cshtml", model);
    }
}
```

`ImageWidgetViewModel` marks `IsMisconfigured` as `true` when no asset is selected, the referenced content item cannot be found, or the attached file is not a supported image format:

```csharp title="ImageWidgetViewModel.cs"
using System.Diagnostics.CodeAnalysis;

using CMS.Helpers;

using TrainingGuides.Web.Features.ResponsiveImages.Models;
using TrainingGuides.Web.Features.Shared.Models;

namespace TrainingGuides.Web.Features.ResponsiveImages.Widgets.ImageWidget;

/// <summary>
/// View model for the "Image" widget.
/// </summary>
public class ImageWidgetViewModel : IWidgetViewModel
{
    /// <summary>
    /// The selected image and its alt text, or <c>null</c> when no valid asset is available.
    /// </summary>
    public ImageViewModel? Image { get; set; }

    /// <summary>
    /// Code name of the selected image variant, or <c>null</c> for the responsive width series.
    /// </summary>
    public string? ImageVariant { get; set; }

    /// <summary>
    /// Indicates whether the widget lacks a valid image file to render.
    /// </summary>
    [MemberNotNullWhen(false, nameof(Image))]
    public bool IsMisconfigured =>
        Image is null || !ImageHelper.IsImage(Image.Asset.Metadata.Extension);
}
```

When `IsMisconfigured` is `true`, the view displays configuration instructions in Page Builder and preview mode and outputs nothing on the live site. Otherwise, it passes `Model.ImageVariant` to the `variant` attribute of `<tg-responsive-image>`:

```razor title="ImageWidget.cshtml"
@using TrainingGuides.Web.Features.ResponsiveImages.Widgets.ImageWidget

@model ImageWidgetViewModel

@if (Model.IsMisconfigured)
{
    <tg-page-builder-content>
        <div class="c-card md bg-1 u-border-02 text-center">
            <tg-configure-widget-instructions/>
        </div>
    </tg-page-builder-content>
}
else
{
    // These widths assume the widget uses the full available parent container width.
    // You can add manual layout selection or automatic container width detection
    // to the widget to further optimize bandwidth usage.
    string sizes = "(min-width: 1400px) 1296px, (min-width: 1200px) 1116px, "
        + "(min-width: 992px) 936px, (min-width: 768px) 696px, "
        + "(min-width: 576px) 516px, calc(100vw - 24px)";

    <tg-responsive-image asset="@Model.Image.Asset" alt="@Model.Image.AltText"
        variant="@Model.ImageVariant" sizes="@sizes" class="img-fluid" />
}
```

Depending on `Model.ImageVariant`, `<tg-responsive-image>` produces one of two outputs:

- **Known variant on the image:** renders a single `src` URL with that variant's `width` and `height` attributes, omitting `srcset` and `sizes`.
- **_Responsive_ mode (`null`), or a variant missing from the image:** renders the responsive `srcset` width series along with `sizes`. The same fallback applies if a variant code name differs in letter case or is absent from the asset's metadata.

When an editor selects _Fixed variant_ and _Card 4:3_, the widget outputs a single fixed crop. In the sample, `…` replaces the asset URL prefix and the file name is shortened for brevity:

```html
<img class="img-fluid" alt="Farfalle with basil pesto and fresh tomatoes served on a white plate" loading="lazy"
    src="…/Card800x600/eaters-collective_Card800x600.jpg?language=en" width="800" height="600">
```

If an administrator later deletes a variant definition, Xperience retains previously generated variant entries in existing assets' metadata. Images that already have the deleted variant continue to render it, while newer uploads fall back to the responsive width series.

The `sizes` value in `ImageWidget.cshtml` assumes that the widget spans the full width of the page container. Editors can place the widget in any editable area, so in a narrower column, the browser downloads a larger file than the column needs. To size images for multi-column layouts, let editors select the layout in the widget properties, or detect the width of the enclosing column in your section views and pass a matching `sizes` value to the widget.

Use a fixed variant when an image occupies a bounded area such as a card in a grid, and keep _Responsive_ for images that scale across wide sections so they stay sharp on high-density phones and lightweight on desktops.

> **Key:** **Key takeaways**
>
> - Implement `IDropDownOptionsProvider` to list the _Smart crop_ variant definitions with their dimensions.
> - Pair an _Asset_ content item selector with a _Responsive_ / _Fixed variant_ radio group and a variant drop-down that shows only in _Fixed variant_ mode.
> - Pass the variant code name to your responsive image tag helper only in _Fixed variant_ mode. A valid variant renders a single fixed image file, while _Responsive_ mode or a variant missing from the asset falls back to the responsive width series.
> - The widget's `sizes` value assumes the full container width. Narrower columns need a layout-aware `sizes` value to avoid oversized downloads.

## What's next

You can browse the complete widget in the [ImageWidget folder of the finished branch](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished/src/TrainingGuides.Web/Features/ResponsiveImages/Widgets/ImageWidget), the options provider in the [OptionProviders folder](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished/src/TrainingGuides.Web/Features/ResponsiveImages/OptionProviders), and the unit tests in the [ResponsiveImages folder of the test project](https://github.com/Kentico/xperience-by-kentico-training-guides/tree/finished/src/TrainingGuides.Web.Tests/Features/ResponsiveImages). For all configuration options available on form components, see [Reference - Admin UI form components](https://docs.kentico.com/documentation/developers-and-admins/customization/extend-the-administration-interface/ui-form-components/reference-admin-ui-form-components.md).

To help content editors work with focal points and manual crops on each variant, share [Work with image variants and focal point](https://docs.kentico.com/guides/digital-marketing/xperience-essentials/work-with-image-variants-and-focal-point.md) with your team.

If you're upgrading to Xperience by Kentico, see [Optimize images during your upgrade](https://docs.kentico.com/guides/upgrade-to-xbyk/upgrade-deep-dives/optimize-images-during-upgrade.md) to bring image variants and asset optimization into your migrated images.
