
Loading ..
Please wait while we prepare...
5/29/2025
In today's web development landscape, optimizing images is crucial for delivering fast and engaging user experiences. Large, unoptimized images can significantly slow down your Blazor applications, leading to frustrated users and poor SEO rankings. But what if you could automate this process seamlessly within your Blazor projects?
Enter BlazorImage, a powerful and intuitive image optimization library designed specifically for Blazor applications. Whether you're building static websites or interactive server-side applications, BlazorImage provides a comprehensive suite of features to ensure your images are always lean, mean, and lightning-fast.
Manually optimizing images can be a tedious and time-consuming task. Developers often need to juggle multiple tools and techniques to resize, compress, and convert images to the most efficient formats. This process can become even more complex when dealing with responsive designs and the need to serve different image sizes for various devices.
BlazorImage simplifies this entire workflow by providing a developer-friendly way to automatically optimize images directly within your Blazor application. This library handles the heavy lifting, allowing you to focus on building amazing user interfaces without worrying about the intricacies of image optimization.
Integrating BlazorImage into your Blazor project is straightforward.
BlazorImage is available on NuGet:
Using .NET CLI:
dotnet add package BlazorImage --version 1.0.4
Or, add a PackageReference to your .csproj
file:
<PackageReference Include="BlazorImage" Version="1.0.4" />
Import the Namespace:
Add the following to your _Imports.razor
file:
@using BlazorImage
Register Services:
In your Program.cs
file, register the BlazorImage services:
builder.Services.AddBlazorImage();
You can customize various options:
builder.Services.AddBlazorImage(options =>
{
// Output directory for optimized images (relative to wwwroot). Default: "_optimized"
options.OutputDir = "optimized-assets"; // Example: "my-optimized-images"
// Responsive widths (pixels) for generated image variants.
// Default: [480, 640, 768, 1024, 1280, 1536]
options.Sizes = [480, 768, 1024, 1280]; // Adjust to your common breakpoints
// Default image quality (15–100). Lower means more compression.
// Default: 75 | Recommended: 70–80 for a good balance.
options.DefaultQuality = 75;
// Default image output format (jpeg, png, webp, avif).
// Default: webp | Recommended: FileFormat.webp (efficient and widely supported).
options.DefaultFileFormat = FileFormat.webp;
});
Map Middleware:
Ensure the BlazorImage runtime is mapped in Program.cs
to serve the optimized files.
// Add this line to serve optimized images
app.MapBlazorImageRuntime();
// ... other app configurations
// app.Run();
Include Required Assets:
Include the BlazorImage stylesheet and script within your App.razor
file:
CSS (in <head>
):
Your project's main scoped CSS file should be included.
<link rel="stylesheet" href="YourAppName.styles.css" />
JS (before closing </body>
tag):
<script src="_content/BlazorImage/BlazorImage.min.js"></script>
BlazorImage offers a dashboard to manage the image cache, which is especially handy during development.
Enable it in Program.cs
:
#if DEBUG // Recommended to enable only in development
app.MapBlazorImageDashboard("/blazor-image-admin"); // Choose your preferred path
#endif
You can then access it at the path you defined (e.g., /blazor-image-admin
).
<Image>
ComponentThe <Image>
component is how you'll interact with BlazorImage in your .razor
files.
<Image Src="/images/my-photo.jpg" Alt="A clear description of the image" Width="300" Height="200" />
Styling Note: When applying styles, use the
CssClass
parameter instead ofclass
, andStyle
instead ofstyle
.
<Image>
Component ParametersSrc
(string, required): Path to the original image file (relative to wwwroot
).Alt
(string, required): Alternative text for accessibility and SEO.Fill
(bool, optional): If true
, the image fills its parent container while preserving its aspect ratio (like object-fit: cover
). Defaults to false
. Width
and Height
are often best used with Fill="false"
or when AspectRatio
is also set.Width
, Height
(int?, optional): Desired image dimensions in pixels.Priority
(bool, optional): If true
, the image loads eagerly (disables lazy loading) and can enable preload linking. Ideal for critical above-the-fold images. Defaults to false
.DefaultSrc
(string, optional): Path to a fallback image if Src
fails to load, overriding default error messages.Quality
(int?, optional): Sets the optimized image quality (15–100). Overrides the global library setting.Format
(FileFormat?
enum, optional): Specifies the desired output image format (e.g., FileFormat.webp
, FileFormat.jpeg
). Note: AVIF generation can be resource-intensive.Sizes
(string, optional): The sizes
attribute for the <img>
tag, guiding the browser in selecting responsive sources.CssClass
(string, optional): CSS classes for the <img>
tag.Style
(string, optional): Inline styles for the <img>
tag.Caption
(string, optional): Text displayed as a caption below the image.CaptionClass
(string, optional): CSS classes for the image caption.AspectRatio
((int, int)
optional): Defines the aspect ratio (e.g., @(16,9)
for 16:9). Particularly useful with Fill="true"
to maintain proportions.EnableInteractiveState
(bool, optional): Enables state-based interactivity (e.g., loading/error visual cues).Id
(string, optional): Sets a custom ID for the image element. Useful for anchoring, JavaScript interaction, or enabling preload links with Priority="true"
.AdditionalAttributes
(Dictionary<string, object>
, optional): A way to pass any other HTML attributes directly to the tag.1. Responsive Image Filling a Container:
<div style="width: 100%; max-width: 600px; height: 350px;">
<Image Src="/images/wide-banner.jpg" Alt="Promotional Banner" Fill="true" />
</div>
2. Static Dimensions (e.g., Icon or Logo):
<Image Src="/images/app-icon.png" Alt="Application Icon" Width="64" Height="64" />
3. Eager Loading for a Hero Image with Preload:
To preload an image, set an Id
and Priority="true"
. Then, use SectionOutlet
in your <HeadContent>
.
<HeadContent>
<SectionOutlet SectionName="hero-image-id" /> {/* Outlet for the preload link */}
</HeadContent>
<Image Id="hero-image-id" {/* Unique ID for the image */}
Priority="true" {/* Enables eager loading and preload link generation */}
Src="/images/hero-main.jpg"
Alt="Main hero image for the page"
Width="1200"
Height="600" />
4. Custom Format and Quality:
<Image Src="/images/detail-shot.png"
Alt="Detailed product shot"
Format="FileFormat.png"
Quality="90"
Width="800"
Height="600" />
5. Using Sizes
Attribute for Fine-Grained Responsiveness:
Ideal with utility CSS frameworks like Tailwind CSS.
<Image Src="/images/user-avatar.jpg"
Alt="User Avatar"
Sizes="(max-width: 768px) 4rem, 8rem" {/* 4rem on small screens, 8rem otherwise */}
CssClass="rounded-full object-cover"
Fill="true"
Priority="true" />
6. Maintaining Aspect Ratio with Fill
:
<div style="width: 100%; max-width: 500px;">
<Image Src="/images/landscape-photo.jpg"
Alt="Scenic landscape"
AspectRatio="@(16,9)"
Fill="true" />
</div>
7. Image with a Caption:
<Image Src="/images/figure1.jpg"
Alt="Figure 1 showing data flow"
Caption="Figure 1: Data flow diagram."
CaptionClass="text-sm text-gray-600 mt-1 text-center"
Width="650" Height="400" />
<img>