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

Asked

Viewed 601 times

2

I get a byte[] which is an image, and saved in the bank (Postgres) in a column o byte[] whole. Can I compress? Make this smaller byte[]?

  • question: why would I want to compact?

  • not to weigh so much in the bank

  • The solution to this would be to keep the physical path of the image so instead of saving it in the bank

  • I can not keep in physical way, at first it is in the bank

  • At runtime in the application, it is possible to create a Buffer, but in the bank I believe it is not possible

  • 3

    I did not understand the negative votes. Who voted can explain?

  • If the message in question is a Bitmap (.BMP), the compression can produce a good reduction in the number of bytes of your byte[]. Already if it is . JPG, . PNG or . GIF (formats that already compress the image), this reduction may not be significant.

Show 2 more comments

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.