using System.IO.Compression;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Formats.Jpeg;
public static class ImageCompressor
{
// This function takes a base64 string and converts it into a bytes array.
// The bytes array is then saved in memory, is passed into GZIP which compresses it.
// Flush and Close Gzip.
// Then it returns what we saved in memory as an array.
// We then Convert it back into base64 string
public static string Compress(string oldImage)
{
byte[] imageBytes = Convert.FromBase64String(oldImage);
byte[] compressedData = CompressBytes(imageBytes);
string compressedBase64String = Convert.ToBase64String(compressedData);
// For testing
Console.WriteLine(compressedBase64String);
return oldImage;
}
private static byte[] CompressBytes(byte[] inputBytes)
{
using (var ms = new MemoryStream())
{
// using (var gzip = new GZipStream(ms, CompressionMode.Compress))
// {
// gzip.Write(inputBytes, 0, inputBytes.Length);
// }
using (Image image = Image.Load(ms))
{
int width = image.Width / 2;
int height = image.Height / 2;
image.Mutate(x => x.Resize(width, height));
image.Save(outStream, new JpegEncoder());
}
byte[] compressedStream = ms.ToArray();
return compressedStream;
}
}
}