Here’s a drop-in C#/.NET 9 method that takes an uploaded IFormFile, decodes it with SixLabors.ImageSharp, and then generates a BlurHash using the BlurHash.Sharp package.
1) Install NuGet packages
In your project file or via CLI:
<PackageReference Include="SixLabors.ImageSharp" Version="3.*" />
<PackageReference Include="BlurHash.Sharp" Version="1.*" />
or via the .NET CLI:
dotnet add package SixLabors.ImageSharp --version 3.*
dotnet add package BlurHash.Sharp --version 1.*
2) The GenerateBlurHashAsync method
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using BlurHash.ImageSharp; // extension methods
public class BlurHashService
{
/// <summary>
/// Generates a BlurHash string from an uploaded image.
/// </summary>
/// <param name="file">The uploaded image (IFormFile).</param>
/// <param name="componentX">How many X components to use (1–9). Higher = more detail.</param>
/// <param name="componentY">How many Y components to use (1–9). Higher = more detail.</param>
/// <returns>A BlurHash-encoded string.</returns>
public async Task<string> GenerateBlurHashAsync(
IFormFile file,
int componentX = 4,
int componentY = 3)
{
if (file is null)
throw new ArgumentNullException(nameof(file));
if (file.Length == 0)
throw new ArgumentException("Empty file.", nameof(file));
// Load the image into memory. ImageSharp will detect the format automatically.
await using var imageStream = file.OpenReadStream();
using Image<Rgba32> image = await Image.LoadAsync<Rgba32>(imageStream);
// Encode BlurHash. This is provided by BlurHash.Sharp’s ImageSharp extension.
string blurHash = image.Process(img => img.EncodeBlurHash(
xComponents: componentX,
yComponents: componentY));
return blurHash;
}
}
3) How it works
- LoadAsync
SixLabors.ImageSharp decodes your stream into an Image<Rgba32>.
- EncodeBlurHash
The BlurHash.Sharp library adds an extension method under BlurHash.ImageSharp that reads pixel data and runs the standard BlurHash encode algorithm.
- Parameters
componentX / componentY: tuning parameters. Larger values give a more detailed but longer hash string.
4) Example usage in a Controller
[ApiController]
[Route("api/[controller]")]
public class ImagesController : ControllerBase
{
private readonly BlurHashService _blurHashService;
public ImagesController(BlurHashService blurHashService)
=> _blurHashService = blurHashService;
[HttpPost("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{
if (file == null)
return BadRequest("No file uploaded.");
string hash = await _blurHashService.GenerateBlurHashAsync(file);
return Ok(new { BlurHash = hash });
}
}
Now when you POST an image to /api/images/upload, the response will include a "BlurHash" string you can plug into any BlurHash-aware client to render a low-res placeholder. 🎨🚀