Here's a C# function to generate a BlurHash from an IFormFile using .NET 9 and SixLabors.ImageSharp:
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using Blurhash.ImageSharp;
public async Task<string> GenerateBlurHashAsync(IFormFile file)
{
if (file == null || file.Length == 0)
{
throw new ArgumentException("File is null or empty", nameof(file));
}
using var stream = file.OpenReadStream();
using var image = await Image.LoadAsync<Rgba32>(stream);
// Resize image for better performance (BlurHash doesn't need full resolution)
// Typically 32-64 pixels on the longest side is sufficient
const int targetSize = 64;
var (width, height) = CalculateResizedDimensions(image.Width, image.Height, targetSize);
image.Mutate(x => x.Resize(width, height));
// Generate BlurHash with default components (4x3)
// You can adjust these values: more components = more detail but larger hash
var blurHash = Blurhasher.Encode(image, 4, 3);
return blurHash;
}
private (int width, int height) CalculateResizedDimensions(int originalWidth, int originalHeight, int targetSize)
{
if (originalWidth > originalHeight)
{
var ratio = (double)targetSize / originalWidth;
return (targetSize, Math.Max(1, (int)(originalHeight * ratio)));
}
else
{
var ratio = (double)targetSize / originalHeight;
return (Math.Max(1, (int)(originalWidth * ratio)), targetSize);
}
}
You'll need to install the following NuGet packages:
SixLabors.ImageSharp (which you already have)
Blurhash.ImageSharp
Here's an enhanced version with more options and error handling:
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using Blurhash.ImageSharp;
using Microsoft.Extensions.Logging;
public class ImageService
{
private readonly ILogger<ImageService> _logger;
private const int DefaultTargetSize = 64;
private const int DefaultComponentX = 4;
private const int DefaultComponentY = 3;
public ImageService(ILogger<ImageService> logger)
{
_logger = logger;
}
public async Task<string> GenerateBlurHashAsync(
IFormFile file,
int targetSize = DefaultTargetSize,
int componentX = DefaultComponentX,
int componentY = DefaultComponentY)
{
if (file == null || file.Length == 0)
{
throw new ArgumentException("File is null or empty", nameof(file));
}
// Validate components (must be between 1 and 9)
componentX = Math.Clamp(componentX, 1, 9);
componentY = Math.Clamp(componentY, 1, 9);
try
{
using var stream = file.OpenReadStream();
using var image = await Image.LoadAsync<Rgba32>(stream);
// Resize for performance
var (width, height) = CalculateResizedDimensions(
image.Width,
image.Height,
targetSize);
if (width != image.Width || height != image.Height)
{
image.Mutate(x => x.Resize(new ResizeOptions
{
Size = new Size(width, height),
Mode = ResizeMode.Max,
Sampler = KnownResamplers.Lanczos3
}));
}
var blurHash = Blurhasher.Encode(image, componentX, componentY);
_logger.LogInformation(
"Generated BlurHash for file {FileName}: {BlurHash} (components: {X}x{Y})",
file.FileName,
blurHash,
componentX,
componentY);
return blurHash;
}
catch (UnknownImageFormatException ex)
{
_logger.LogError(ex, "Unknown image format for file {FileName}", file.FileName);
throw new InvalidOperationException($"The file '{file.FileName}' is not a valid image format", ex);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error generating BlurHash for file {FileName}", file.FileName);
throw;
}
}
private (int width, int height) CalculateResizedDimensions(int originalWidth, int originalHeight, int targetSize)
{
if (originalWidth > originalHeight)
{
var ratio = (double)targetSize / originalWidth;
return (targetSize, Math.Max(1, (int)(originalHeight * ratio)));
}
else
{
var ratio = (double)targetSize / originalHeight;
return (Math.Max(1, (int)(originalWidth * ratio)), targetSize);
}
}
}
Example usage in a controller:
[ApiController]
[Route("api/[controller]")]
public class ImageController : ControllerBase
{
private readonly ImageService _imageService;
public ImageController(ImageService imageService)
{
_imageService = imageService;
}
[HttpPost("blurhash")]
public async Task<IActionResult> GenerateBlurHash(IFormFile file)
{
try
{
var blurHash = await _imageService.GenerateBlurHashAsync(file);
return Ok(new { blurHash });
}
catch (ArgumentException ex)
{
return BadRequest(new { error = ex.Message });
}
catch (InvalidOperationException ex)
{
return BadRequest(new { error = ex.Message });
}
}
}
Key points about the implementation:
- The function resizes the image before generating the BlurHash for better performance (BlurHash doesn't need full resolution)
- Default components are 4x3, which provides a good balance between hash size and quality
- The enhanced version includes proper error handling and logging
- You can adjust the component values (1-9) for more or less detail in the hash
- The function uses
Rgba32 pixel format for compatibility with the BlurHash library
Remember to register the service in your Program.cs:
builder.Services.AddScoped<ImageService>();