Added user image caching

This commit is contained in:
2025-11-20 19:22:12 +01:00
parent 6be72c1f5c
commit 9767feb3e2
3 changed files with 27 additions and 30 deletions

View File

@@ -1,5 +1,4 @@
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Formats.Webp;
using SixLabors.ImageSharp.Formats;
@@ -7,36 +6,33 @@ namespace Berufsschule_HAM.Helpers;
public static class ImageHelper
{
public static string ResizeAndConvertToBase64(byte[] imageBytes, int size = 32)
public static Dictionary<int, Dictionary<string, byte[]>> ImageCache = [];
public static byte[] ResizeAndConvertToWebp(string imageString, int size = 32)
{
using var inputStream = new MemoryStream(imageBytes);
var decoderOptions = new DecoderOptions
if (ImageCache.TryGetValue(size, out Dictionary<string, byte[]>? sizeCache)
&& sizeCache.TryGetValue(imageString, out byte[]? result) && result.Length > 0)
{
TargetSize = new Size(size, size)
};
using var image = Image.Load(decoderOptions, inputStream);
int minDimension = Math.Min(image.Width, image.Height);
var cropRectangle = new Rectangle(
(image.Width - minDimension) / 2,
(image.Height - minDimension) / 2,
minDimension,
minDimension);
image.Mutate(x =>
return result;
}
if (sizeCache is null) ImageCache[size] = [];
lock (ImageCache[size])
{
x.Crop(cropRectangle);
x.Resize(new ResizeOptions
byte[] imageBytes = Convert.FromBase64String(imageString);
using var inputStream = new MemoryStream(imageBytes);
var decoderOptions = new DecoderOptions
{
Size = new Size(size, size),
Mode = ResizeMode.Crop
});
});
TargetSize = new Size(size, size),
SkipMetadata = true
};
using var outputStream = new MemoryStream();
image.Save(outputStream, new WebpEncoder());
return Convert.ToBase64String(outputStream.GetBuffer(), 0, (int)outputStream.Length);
using var image = Image.Load(decoderOptions, inputStream);
using var outputStream = new MemoryStream();
image.Save(outputStream, new WebpEncoder());
result = outputStream.ToArray();
ImageCache[size][imageString] = result;
}
return result;
}
}