Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress a Byte array without stream or system io

Tags:

I'm trying to encode an image into a byte array and send it to a server. the encoding and sending parts wok fine but my problem is that the byte array is too large and takes too long to send so I thought compressing it would make it go faster. but the actual problem is that I CAN NOT use system.io or streams. and I'm targeting .net 2.0. Thank you.

like image 200
Henjin Avatar asked Aug 28 '16 13:08

Henjin


People also ask

Can you compress byte array?

You can use the Deflater and Inflater classes in the java. util. zip package to compress and decompress data in a byte array, respectively.

Is a byte array a stream?

Streams are commonly written to byte arrays. The byte array is the preferred way to reference binary data in . NET. It can be used to data like the contents of a file or the pixels that make up the bitmap for an image.


1 Answers

using System.IO; using System.IO.Compression; 

code:

public static byte[] Compress(byte[] data) {     MemoryStream output = new MemoryStream();     using (DeflateStream dstream = new DeflateStream(output, CompressionLevel.Optimal))     {         dstream.Write(data, 0, data.Length);     }     return output.ToArray(); }  public static byte[] Decompress(byte[] data) {     MemoryStream input = new MemoryStream(data);     MemoryStream output = new MemoryStream();     using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))     {         dstream.CopyTo(output);     }     return output.ToArray(); } 

Updated

Use 7zip library:
http://www.splinter.com.au/compressing-using-the-7zip-lzma-algorithm-in/

// Convert the text into bytes byte[] DataBytes = ASCIIEncoding.ASCII.GetBytes(OriginalText);  // Compress it byte[] Compressed = SevenZip.Compression.LZMA.SevenZipHelper.Compress(DataBytes);  // Decompress it byte[] Decompressed = SevenZip.Compression.LZMA.SevenZipHelper.Decompress(Compressed); 
like image 71
mjb Avatar answered Oct 20 '22 00:10

mjb