Files
Berufsschule_HAM/src/Helpers/ImageHelper.cs

41 lines
1.3 KiB
C#

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Formats.Jpeg;
using System.IO;
using SixLabors.ImageSharp.Formats.Gif;
using SixLabors.ImageSharp.Processing.Processors.Quantization;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.Formats.Webp;
namespace Berufsschule_HAM.Helpers;
public static class ImageHelper
{
public static string ResizeAndConvertToBase64(byte[] imageBytes, int size = 32)
{
using var inputStream = new MemoryStream(imageBytes);
using var image = Image.Load(inputStream);
// Optional: crop to square before resize
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 =>
{
x.Crop(cropRectangle);
x.Resize(new ResizeOptions
{
Size = new Size(size, size),
Mode = ResizeMode.Crop
});
});
using var outputStream = new MemoryStream();
image.Save(outputStream, new WebpEncoder(){});
return Convert.ToBase64String(outputStream.ToArray());
}
}