Table of Contents

Image Handler

How to use the GetImage service and the ImageFileViewModel extensions to resize, convert, crop, and serve responsive images from Razor templates

The Dynamicweb Image Handler – GetImage.ashx – generates images dynamically based on a source file in the file archive. Instead of manually preparing thumbnails and scaled variants, you request the original image with a set of parameters, and the image handler resizes, crops, and converts it on the fly:

<img src="/Admin/Public/GetImage.ashx?Image=/Files/Images/product.jpg&Width=800&Format=webp" alt="Product">

Generated images are cached on disk in /Files/Cache.net/Images and served from there on subsequent requests — when the original file changes, variants are lazily regenerated on the next request. Responses carry Cache-Control and ETag headers, so browsers and CDNs cache them efficiently — cache duration, default WebP quality, and missing-image behavior are configured in Settings > System > Web & HTTP > Image handler, and request limits (max width, allowed formats, etc.) under Image validation. For how the caches interact — and why a replaced same-name image doesn't update for returning visitors — see Understanding image and browser caches.

There are two ways to use the image handler from templates:

  1. Directly — build the GetImage.ashx URL yourself with query parameters. Full control, useful anywhere.
  2. Through ImageFileViewModel and its extension methods — the recommended approach in Razor templates. The extensions build correct URLs for you, handle focal points, ratios, SVG passthrough, and responsive srcset/sizes attributes.

Parameters

The following query string parameters can be used with GetImage.ashx:

Parameter Value Notes
Image Path to an image file in the file archive, e.g. /Files/Images/photo.jpg Required. Legacy alias: fmImage_path
AlternativeImage Path to an image file Served instead if the primary image does not exist. Legacy alias: altFmImage_path. See missing images below
Width 1–99999 Target width in pixels. Provide Width, Height, or both
Height 1–99999 Target height in pixels
Ratio Fraction or decimal, e.g. 16/9 or 1.78 Requires Width. Calculates Height from the ratio and automatically sets crop mode to CenterOrFocal (7). Handy for uniform card grids
Format webp, jpg, png, gif, bmp, tiff, pdf Converts the image to another format. See formats below
Quality 1–100, or -1 Compression quality for webp and jpg. -1 = lossless (WebP only). If omitted for WebP, the Default webp quality global setting applies (65 unless changed)
Compression 1–100 Legacy alias for Quality (used for JPEG). Quality wins if both are present
Crop 0–7 Crop mode — see crop modes below. Accepts the numeric value or the name, e.g. Crop=7 or Crop=CenterOrFocal
x, y −100 to 100 Focal point coordinates relative to the image center — see focal points below
Colors 1–256 Color depth; mainly relevant for GIF output
ColorSpace RGB, CMYK, Grayscale Default is RGB
Resolution 72–300 Output DPI. Only relevant for print scenarios — leave out for web
FillCanvas True/False With Crop=5 and both dimensions set, fills the unused part of the box with the Background color instead of shrinking the canvas
Background Hex color, e.g. FF0000 Background color used with FillCanvas and behind transparent PNGs when converting to formats without transparency
DoNotUpscale True/False Default True — images are never made larger than the original. With Crop=5, upscaling is always prevented regardless of this parameter
FileName A filename with extension Sets the filename in the Content-Disposition header — the name the browser suggests when saving
ForceDownload True/False Serves the image as an attachment (download) instead of displaying it inline
DoNotCache True/False Bypasses the image cache and regenerates on every request. Only for debugging — never in production markup

Crop modes

The crop mode defines what happens when the requested Width/Height proportions differ from the original image:

Value Name Behavior
0 Center Crops around the center of the image
1 LowerLeft Keeps as much as possible from the lower-left corner
2 UpperLeft Keeps as much as possible from the upper-left corner
3 UpperRight Keeps as much as possible from the upper-right corner
4 LowerRight Keeps as much as possible from the lower-right corner
5 KeepAspectRatio No cropping — the image is resized to fit inside the width/height box, preserving its aspect ratio. If only one dimension is given, the other follows automatically. Never upscales
6 Fit No cropping — the image is stretched to fill the box exactly, distorting it if proportions differ
7 CenterOrFocal Like Center, but crops around the image's focal point when one is set. The best default for art-directed cropping

Missing images and alternative images

If the file in Image does not exist, the image handler falls back to AlternativeImage — useful for placeholder images ("photo coming soon"). If neither exists, the response is 404 Not Found.

By default the alternative image is served with a 200 OK status. The global setting Send 404 header with alternative image changes this so the fallback is served with a 404 status instead — visitors still see the placeholder, but crawlers and monitoring detect the missing original. See the Image handler settings for details.

Formats and when to use them

The Format parameter converts images on the fly, which means editors can upload whatever they have — a big PNG or JPEG — and the template decides the optimal delivery format. Best practices for the web:

Content Recommended format Why
Photos, banners, product images WebP 25–35% smaller than JPEG at equivalent visual quality, supports transparency. This is the default output format used by the ImageFileViewModel extensions
Logos, icons, illustrations SVG (don't convert) Vector — razor-sharp at any size and usually tiny. The image handler doesn't process SVGs; serve them directly (the extensions do this automatically)
Screenshots, graphics with sharp text, when lossless matters PNG — or WebP with Quality=-1 (lossless) Avoids compression artifacts around hard edges
Legacy browser requirements JPEG Universally supported. Note: when a browser doesn't advertise WebP support, the image handler automatically serves JPEG instead of WebP — you don't need to handle the fallback yourself

Practical guidelines:

  • Quality 65–75 is the sweet spot for WebP and JPEG photos. Higher values grow files quickly with little visible gain; the difference between quality 75 and 95 is often invisible but doubles the file size.
  • Never serve images larger than they are displayed. A 4000-pixel original shown in a 400-pixel column wastes bandwidth and hurts Core Web Vitals — always pass a Width matched to the layout (see responsive images below).
  • Always set width/height attributes (or a CSS aspect-ratio) on <img> tags so the browser reserves space before the image loads — this prevents layout shift (CLS).
  • Lazy-load below-the-fold images with loading="lazy" — but never the hero/LCP image. For the main above-the-fold image, use fetchpriority="high" instead so the browser prioritizes it.
  • TIFF, BMP, and PDF output exist for special integration scenarios (print, feeds) — don't use them for web pages.

Sources and further reading: MDN image file type guide, web.dev on lazy loading, Request Metrics: high-performance images.

Using the image handler in Razor templates

In DW10 view model templates, images are represented by ImageFileViewModel — a file reference that also carries the image's focal point and aspect ratio as configured by the editor in the backend. The ImageFileViewModelExtensions class adds a set of extension methods that turn a view model into ready-to-use GetImage URLs and attributes.

The view model, settings class, and extensions all live in Dynamicweb.Frontend; the ImageType enum lives in Dynamicweb.Imaging, and the product media extensions in Dynamicweb.Ecommerce.ProductCatalog:

@using Dynamicweb.Frontend
@using Dynamicweb.Imaging
@using Dynamicweb.Ecommerce.ProductCatalog

You typically get an ImageFileViewModel from the view model you're already working with:

@* From an item field on a paragraph or page *@
@if (Model.Item.TryGetImageFile("Image", out ImageFileViewModel image))
{
    <img src="@image.ToGetImage()" alt="" />
}

@* From a product's media (ProductViewModel) *@
@if (product.DefaultImage.TryGetImageFileViewModel(out ImageFileViewModel productImage))
{
    <img src="@productImage.ToGetImage()" alt="@product.Name" />
}

@* From page properties *@
@if (Model.TryGetImageFile(out ImageFileViewModel pageImage)) { ... }

Similar TryGet... methods exist on navigation nodes (TryGetImageFile, TryGetIconFile), users, and user groups.

ToGetImage — generate a GetImage URL

ToGetImage() is the core method. Without arguments it returns a GetImage URL with sensible defaults — WebP format and a width of 1680 pixels:

<img src="@image.ToGetImage()" alt="" />
@* → /Admin/Public/GetImage.ashx?width=1680&format=webp&image=/Files/Images/photo.jpg *@

It does more than concatenate strings:

  • If the file is an SVG (or another type GetImage can't resize), it returns the file's direct path untouched — no broken conversions.
  • If the editor set a focal point on the image, x and y parameters are included automatically.
  • If the editor set an aspect ratio on the image, the height is calculated from it and crop mode CenterOrFocal is applied.
  • If the model is null or has no path, it returns null — safe to use with null-conditional rendering.

Pass a GetImageSettings object to control the output:

@{
    var settings = new GetImageSettings
    {
        Width = 800,            // target width in pixels
        Ratio = "16/9",         // height is calculated: 800 / (16/9) = 450
        Quality = 70,           // WebP/JPEG quality
        Format = ImageType.WebP // WebP is also the default
    };
}
<img src="@image.ToGetImage(settings)" width="800" height="450" alt="" />

GetImageSettings properties:

Property Effect
Width / Height Target dimensions in pixels. If neither is set, width defaults to 1680
Ratio "16/9", "1/1", or a decimal like "2.33". With Width set, calculates the height. An editor-defined ratio on the image itself takes precedence
RatioDefault Fallback ratio used only when the image has no editor-defined ratio
Quality 1–100; -1 for lossless WebP. Recommended 65–75
Format ImageType.WebP (default), Jpg, Png, Gif, Bmp — Auto resolves to WebP
Crop A CropMode value. Defaults to KeepAspectRatio at generation time; automatically CenterOrFocal when a ratio is applied
DoNotUpscale Defaults to true. Automatically set to false when a ratio is applied, so cards fill their box

ToBackgroundStyle — CSS background images

For hero sections and banners rendered as CSS backgrounds, ToBackgroundStyle() produces a complete inline style — including background-position derived from the image's focal point, so the important part of the image stays in view as the section is cropped by the viewport:

<section style="@image.ToBackgroundStyle()">
    ...
</section>
@* → background-image: url(/Admin/Public/GetImage.ashx?width=1680&...);background-position: 25% 50%;background-size: cover; *@

You can pass GetImageSettings and tweak the style parts:

@image.ToBackgroundStyle(new GetImageSettings { Width = 1920, Quality = 60 }, includeBackgroundPosition: true, backgroundSize: "cover")

Focal points

Editors set focal points on images with the image selector in the backend — marking the subject of the photo (a face, a product) that must stay visible when the image is cropped. Focal coordinates run from −100 to 100 on each axis with 0,0 at the image center.

The extensions use focal points automatically, but the view model also exposes them for custom scenarios:

@if (image.HasFocalPoint())
{
    @* As GetImage parameters: x=25&y=-10 *@
    <img src="/Admin/Public/GetImage.ashx?Image=@image.Path&Width=800&Height=450&Crop=7&@image.GetFocalPointParameters()" alt="" />
}

@* As CSS percentages for object-fit cropping — returns "50% 50%" when no focal point is set *@
<img src="@image.ToGetImage()" style="object-fit: cover; object-position: @image.GetFocalPointPercentage()" alt="" />

Focal points are used by all crop modes except KeepAspectRatio (5) — most predictably with CenterOrFocal (7).

Other helpers

@if (image.IsSvg())
{
    @* Inline it, or serve directly — GetImage isn't involved for SVGs *@
    <img src="@image.Path" alt="" />
}

No ImageFileViewModel? Create your own

Sometimes you're in a context where no ImageFileViewModel exists — the image path comes from a website setting, a custom field, an integration, or a plain string. Rather than falling back to hand-building GetImage URLs, create an instance yourself and get all the extension methods for free:

@{
    // Path drives the URL; Name is used to detect the file type (SVG passthrough etc.)
    var heroImage = new ImageFileViewModel
    {
        Path = "/Files/Images/campaigns/summer.jpg",
        Name = "summer.jpg"
    };
}
<div style="@heroImage.ToBackgroundStyle(new GetImageSettings { Width = 1920 })">...</div>

You can also enrich it with a focal point or ratio if you know them:

@{
    var cardImage = new ImageFileViewModel
    {
        Path = imagePathFromSetting,
        Name = System.IO.Path.GetFileName(imagePathFromSetting),
        Ratio = "4/3",   // all cards get the same proportions
        FocalX = 20,     // slightly right of center
        FocalY = 35      // above center
    };
}
<img src="@cardImage.ToGetImage(new GetImageSettings { Width = 640 })" alt="" />

This keeps every image on the solution flowing through the same pipeline — consistent formats, quality, caching, and focal-point handling — instead of a mix of raw file paths and hand-crafted query strings.

Tip

Set Name when you create the instance. ToGetImage() uses the file name to decide whether the file can be resized at all — without it, the extension can't recognize SVGs and other non-resizable types.

Responsive images

Serving one huge image to every device wastes bandwidth on phones and hurts loading performance everywhere. The srcset/sizes mechanism lets the browser pick the right size — and it has recently become much simpler to use.

The modern, simple approach: sizes="auto" with lazy loading

Historically, the hard part of responsive images was the sizes attribute — manually describing your layout's breakpoints in media-query syntax. That era is ending: for lazy-loaded images, browsers can now measure the actual rendered size of the image before requesting it, and pick from srcset automatically. You opt in with sizes="auto" (see The end of responsive images for the background).

The template's only job is to offer a range of widths — which ToGetImage makes trivial:

@{
    GetImageSettings Size(int width) => new GetImageSettings { Width = width, Ratio = "4/3" };
}
<img src="@image.ToGetImage(Size(800))"
     srcset="@image.ToGetImage(Size(400)) 400w,
             @image.ToGetImage(Size(800)) 800w,
             @image.ToGetImage(Size(1200)) 1200w,
             @image.ToGetImage(Size(1680)) 1680w"
     sizes="auto, (max-width: 576px) 100vw, 50vw"
     loading="lazy"
     width="800" height="600"
     alt="" />

How it works:

  • srcset lists the same image at several widths, each annotated with its pixel width (800w).
  • sizes="auto" tells supporting browsers: measure the layout, then choose. It must be the first entry and is only valid together with loading="lazy" — lazy images are requested after layout, which is what makes the measurement possible.
  • The entries after auto are the fallback for browsers that don't support it yet — they read the list the classic way. Keep them roughly honest (100vw on mobile, the approximate column width on desktop) but don't agonize over precision.
  • width/height reserve layout space and prevent content jumping when the image arrives.

Above the fold: don't lazy-load your hero

sizes="auto" depends on lazy loading, and lazy loading is wrong for the first image the visitor sees (the LCP element). For hero images, write explicit sizes and boost priority instead:

<img src="@image.ToGetImage(new GetImageSettings { Width = 1920, Quality = 60 })"
     srcset="@image.ToGetImage(new GetImageSettings { Width = 960 }) 960w,
             @image.ToGetImage(new GetImageSettings { Width = 1920 }) 1920w,
             @image.ToGetImage(new GetImageSettings { Width = 2560 }) 2560w"
     sizes="100vw"
     fetchpriority="high"
     width="1920" height="1080"
     alt="" />

A full-viewport hero is the one case where classic sizes is trivial anyway: it's 100vw.

Grid-based helpers: ToSrcSet and ToSizesVW

For images placed in a 12-column grid — typical for card lists and paragraph layouts — the extensions can generate both attributes from column spans, using standard breakpoints (mobile ≤576px, tablet ≤992px, desktop 1680px reference width):

@* A card that spans 4 of 12 columns on desktop and tablet, full width (12) on mobile *@
<img src="@image.ToGetImage()"
     srcset="@image.ToSrcSet(4, 12)"
     sizes="auto, @image.ToSizesVW(4, 12)"
     loading="lazy"
     alt="" />

ToSrcSet(desktopColumns, mobileColumns) produces one candidate per breakpoint (e.g. ...width=560... 560w, ...width=331... 331w, ...width=576... 576w), and ToSizesVW(desktopColumns, mobileColumns) the matching viewport-relative sizes ((max-width: 576px) 100vw, (max-width: 992px) 33.3vw, 33.3vw). Overloads with a tabletColumns parameter let you differentiate the tablet span, and ToSrcSet accepts a base GetImageSettings so quality, ratio, and crop apply to every candidate.

Responsive image checklist

  • Generate 3–5 width variants — steps of roughly 2× area (e.g. 400/800/1200/1680) beat many tiny steps.
  • Let WebP be the format (the extensions' default) and keep quality at 65–75.
  • loading="lazy" + sizes="auto" (with fallback values) for everything below the fold.
  • fetchpriority="high" + explicit sizes for the hero/LCP image — never lazy-load it.
  • Always reserve space with width/height attributes or CSS aspect-ratio.
  • Use Ratio (or the editor-set ratio) so all variants share identical proportions — mixed proportions in one srcset break the browser's selection math.
To top