Example #1
0
        /// <summary>
        /// Compresses the specified byte range using the
        ///  specified compressionLevel (constants are defined in
        ///  java.util.zip.Deflater).
        /// </summary>
        public static byte[] Compress(byte[] value, int offset, int length, int compressionLevel)
        {
            /* Create an expandable byte array to hold the compressed data.
             * You cannot use an array that's the same size as the orginal because
             * there is no guarantee that the compressed data will be smaller than
             * the uncompressed data. */
            var bos = new ByteArrayOutputStream(length);

            Deflater compressor = SharpZipLib.CreateDeflater();

            try
            {
                compressor.SetLevel(compressionLevel);
                compressor.SetInput(value, offset, length);
                compressor.Finish();

                // Compress the data
                var buf = new byte[1024];
                while (!compressor.IsFinished)
                {
                    int count = compressor.Deflate(buf);
                    bos.Write(buf, 0, count);
                }
            }
            finally
            {
            }

            return bos.ToArray();
        }
Example #2
0
        /// <summary>
        /// Decompress the byte array previously returned by
        ///  compress
        /// </summary>
        public static byte[] Decompress(byte[] value, int offset, int length)
        {
            // Create an expandable byte array to hold the decompressed data
            var bos = new ByteArrayOutputStream(length);

            Inflater decompressor = SharpZipLib.CreateInflater();

            try
            {
                decompressor.SetInput(value);

                // Decompress the data
                var buf = new byte[1024];
                while (!decompressor.IsFinished)
                {
                    int count = decompressor.Inflate(buf);
                    bos.Write(buf, 0, count);
                }
            }
            finally
            {
            }

            return bos.ToArray();
        }