Is there any way to compress data stored in byte []?

2

I get a byte[] that is an image, and saved in the database (Postgres) in a column byte[] todo. How can I compress? Leave lower this byte[] ?

    
asked by anonymous 15.04.2014 / 19:10

1 answer

6

Try something like the following code: (Do your tests and make sure everything is correct.)

public static byte[] Compress(byte[] data)
{
    // Fonte: http://stackoverflow.com/a/271264/194717
    using (var compressedStream = new MemoryStream())
    using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
    {
        zipStream.Write(data, 0, data.Length);
        zipStream.Close();
        return compressedStream.ToArray();
    }
}

public static byte[] Decompress(byte[] bSource)
{
    // Fonte: http://stackoverflow.com/questions/6350776/help-with-programmatic-compression-decompression-to-memorystream-with-gzipstream
    using (var inStream = new MemoryStream(bSource))
    using (var gzip = new GZipStream(inStream, CompressionMode.Decompress))
    using (var outStream = new MemoryStream())
    {
        gzip.CopyTo(outStream);
        return outStream.ToArray();
    }
}
    
15.04.2014 / 19:30