C#C
C#4y ago
Shane

❔ Help compressing image!

I need help compressing a jpeg that comes in as a base64string. It currently gets compressed via gzip but this is wrong! I want to shrink the image down therefore lowering the res:

using System.IO.Compression;

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);
            }

            byte[] compressedStream = ms.ToArray();
            return compressedStream;
        }
    }
}
Was this page helpful?