
Supercharge Your Blazor App: Effortless Image Optimization with BlazorImage
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.
The Challenge of Image Optimization in Blazor
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.
Introducing BlazorImage: Your Blazor Image Optimization Ally
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.
Features
- 🖼️ Optimized Static Assets: Generates highly optimized images directly as static assets for blazing-fast loading.
- 🗜️ Image Compression: Reduces image sizes significantly (often by 70-90%).
- 📏 Responsive Images: Automatically creates multiple image sizes for different screen widths, optimizing loading times and performance across devices.
- 📸 Image Formats: Supports modern formats like WebP and AVIF for superior compression and quality, along with traditional JPEG and PNG.
- ⚪ Placeholder: Generates a low-quality placeholder image to improve user experience during loading.
- 🔄 Lazy Loading: Defers loading of off-screen images, improving initial page load times.
- 🗄️ Intelligent Caching: Implements long-term caching with efficient revalidation to ensure fresh content without redundant processing.
- ⚡ Versatile Rendering: Supports both Static and Interactive rendering modes in Blazor apps.
🚀 Getting Started
Prerequisites
- .NET 9.0 SDK or higher
Limitations
- Currently supports .NET 9.0 or higher only.
- Supports local images only at this time. Remote image support is planned for future releases.
- Blazor WebAssembly is not yet supported.
Installation
Install BlazorImage using the .NET CLI or NuGet Package Manager.
Using .NET CLI:
dotnet add package BlazorImage --version 1.0.3
Using NuGet Package Manager:
<PackageReference Include="BlazorImage" Version="1.0.3" />
Next, add the BlazorImage namespace to your _Imports.razor
file:
@using BlazorImage
Register Services
To enable BlazorImage, register its services in your Program.cs
file:
builder.Services.AddBlazorImage();
You can further configure BlazorImage using the following options within the AddBlazorImage
method:
builder.Services.AddBlazorImage(options =>
{
// Path for storing processed images. Default: "_optimized"
options.OutputDir = "Path";
// Array of sizes for image configuration (in pixels). Default: [480, 640, 768, 1024, 1280, 1536]
options.Sizes = new int[] { 640, 1024, 1280 }; // Recommended: Covers common screen widths for responsive design (e.g., [xs, sm, md, lg, xl, 2xl, ...])
// Default quality for processed images (Range: 15-100). Default: 75
options.DefaultQuality = 70; // Recommended: 70-80 (Good balance between quality and file size)
// Default file format for processed images (e.g., "webp", "jpeg"). Default: "webp"
options.DefaultFileFormat = FileFormat.webp; // Recommended: FileFormat.webp (Offers superior compression and quality where supported)
// Aspect ratio width for images. Default: 1.0
options.AspectWidth = 1.0; // Recommended: 1.0 (Maintain original aspect ratio by default)
// Aspect ratio height for images. Default: 1.0
options.AspectHeight = 1.0; // Recommended: 1.0 (Maintain original aspect ratio by default)
// Absolute expiration time for cached images (relative to now). Default: 720 hours (30 days)
options.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(720);
// Sliding expiration time for cached images. Default: null (disabled)
options.SlidingExpiration = null;
});
Map Runtime Endpoint
Configure static file serving for the optimized images by calling the extension method in your Program.cs
file:
app.MapBlazorImageRuntime();
Example usage:
// Add BlazorImage Dashboard (optional - for development)
app.MapBlazorImageDashboard("/blazor/images");
// 👇 Add this line to serve optimized images
app.MapBlazorImageRuntime();
app.MapStaticAssets();
Dashboard Endpoints
BlazorImage provides optional dashboard endpoints to manage cached optimized images, allowing actions like clearing the cache. You can map this endpoint in your Program.cs
file:
app.MapBlazorImageDashboard("/blazor/images"); // Example path
Blazor Integration
Include the BlazorImage stylesheet and script within your App.razor
file:
CSS:
<link rel="stylesheet" href="@Assets["YourProjectName.styles.css"]" />
JS:
<script src="_content/BlazorImage/BlazorImage.min.js"></script>
Note: Replace "YourProjectName"
with the actual name of your Blazor project.
Image
Component
The <Image>
component is the primary way to display optimized images in your Blazor application. Simply reference it in your .razor
files. Here's a basic example:
<Image Src="/images/my-image.jpg" Alt="A beautiful landscape" Width="200" Height="200" />
This will render optimized versions of the image located at /images/my-image.jpg
from the wwwroot
folder.
Key Parameters:
The <Image>
component offers several parameters to customize its behavior:
Src
(required): The path to the original image file (relative towwwroot
). BlazorImage will handle the optimization.Alt
(required): Alternative text for the image, crucial for accessibility.Fill
(optional, boolean): Iftrue
, the image will attempt to fill its parent container while maintaining its aspect ratio (similar to CSSobject-fit: cover
). Defaults tofalse
.Width
,Height
: Required for fixed-size images whenFill
isfalse
. Not used ifFill
istrue
.Priority
(optional, boolean): Iftrue
, disables lazy loading, ensuring the image loads immediately with high priority. Defaults tofalse
(enabling lazy loading).Title
(optional, string): The title attribute for the image.CssClass
(optional, string): Apply custom CSS classes to the<img>
tag.Style
(optional, string): Apply inline styles to the<img>
tag.Quality
(optional, int): The desired quality of the optimized image (15-100). Defaults to the library's configuredDefaultQuality
.Format
(optional,FileFormat
enum): The desired output format (e.g.,FileFormat.webp
,FileFormat.jpeg
,FileFormat.png
,FileFormat.avif
). Defaults to the library's configuredDefaultFileFormat
.- Note: Generating AVIF images might require a second build or processing step due to encoding complexity.
Sizes
(optional, string): Thesizes
attribute for responsive images, defining image sizes for different viewport conditions.Caption
(optional, string): Text to display as a caption below the image.CaptionClass
(optional, string): Apply custom CSS classes to the image caption.DefaultSrc
(optional, string): Path to a fallback image to display if the original image fails to load.EnableDeveloperMode
(optional, boolean): Enables a developer information panel (likely for debugging purposes).EnableInteractiveState
(optional, boolean): Enables interactive state for the component.AdditionalAttributes
(optional,Dictionary<string, object>
): Allows you to pass any other HTML attributes directly to the underlying<img>
tag.
Usage Examples:
Filling the container:
<div style="width: 400px; height: 400px;">
<Image Src="/images/my-wide-image.jpg" Alt="Wide image" Fill="true" />
</div>
Specifying width and height:
<Image Src="/images/my-logo.png" Alt="Company logo" Width="80" Height="80" />
Disabling lazy loading for a hero image:
<Image Src="/images/hero.jpg" Alt="Hero image" Priority="true" />
Requesting a specific format and quality:
<Image Src="/images/high-quality.png" Alt="High quality image" Format="FileFormat.png" Quality="80" />
Sizes Attribute (Tailwind CSS Example):
<div className="relative">
<div class="w-44 h-44 md:w-52 md:h-52">
<Image Src="/images/avatar.jpg"
Alt="Avatar image"
Sizes="(max-width: 768px) 8rem, 13rem"
CssClass="rounded-full object-cover"
Fill="true"
Priority="true" />
</div>
</div>
Sizes Attribute (Generic Example):
<Image Src="/images/responsive.jpg"
Alt="Responsive image"
Sizes="(max-width: 600px) 100vw, (max-width: 1200px) 80vw, 1200px" />
Adding a caption:
<Image Src="/images/product.jpg" Alt="Product shot" Caption="The latest product" CaptionClass="product-caption" />
Using a default image:
<Image Src="/images/non-existent.jpg" Alt="Fallback image" DefaultSrc="/images/default.jpg" />
By utilizing these parameters, you can effectively manage and optimize images within your Blazor applications using the <Image>
component.