Write() public method

Writes bytes from an array to the compressed stream.
public Write ( byte buffer, int offset, int count ) : void
buffer byte /// The byte array ///
offset int /// The offset into the byte array where to start. ///
count int /// The number of bytes to write. ///
return void
Example #1
21
        public byte[] Compress(byte[] bytData, params int[] ratio)
        {
            int compRatio = 9;
            try
            {
                if (ratio[0] > 0)

                {
                    compRatio = ratio[0];
                }
            }
            catch
            {
                throw;
            }

            try
            {
                var ms = new MemoryStream();
                var defl = new Deflater(compRatio, false);
                Stream s = new DeflaterOutputStream(ms, defl);
                s.Write(bytData, 0, bytData.Length);
                s.Close();
                byte[] compressedData = ms.ToArray();
                 return compressedData;
            }
            catch
            {
                throw;

            }
        }
        public void TestInflateDeflate()
        {
            MemoryStream ms = new MemoryStream();
            Deflater deflater = new Deflater(6);
            DeflaterOutputStream outStream = new DeflaterOutputStream(ms, deflater);

            byte[] buf = new byte[1000000];
            System.Random rnd = new Random();
            rnd.NextBytes(buf);

            outStream.Write(buf, 0, buf.Length);
            outStream.Flush();
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            InflaterInputStream inStream = new InflaterInputStream(ms);
            byte[] buf2 = new byte[buf.Length];
            int    pos  = 0;
            while (true) {
                int numRead = inStream.Read(buf2, pos, 4096);
                if (numRead <= 0) {
                    break;
                }
                pos += numRead;
            }

            for (int i = 0; i < buf.Length; ++i) {
                Assertion.AssertEquals(buf2[i], buf[i]);
            }
        }
		// netz.compress.ICompress implementation

		public long Compress(string file, string zipFile)
		{
			long length = -1;
			FileStream ifs = null;
			FileStream ofs = null;
			try
			{
				ifs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
				ofs = File.Open(zipFile, FileMode.Create, FileAccess.Write, FileShare.None);
				DeflaterOutputStream dos = new DeflaterOutputStream(ofs, new Deflater(Deflater.BEST_COMPRESSION));
				byte[] buff = new byte[ifs.Length];
				while(true)
				{
					int r = ifs.Read(buff, 0, buff.Length);
					if(r <= 0) break;
					dos.Write(buff, 0, r);
				}
				dos.Flush();
				dos.Finish();
				length = dos.Length;
				dos.Close();
			}
			finally
			{
				if(ifs != null) ifs.Close();
				if(ofs != null) ofs.Close();
			}
			return length;
		}
Example #4
0
 public static byte[] CompressZlib(byte[] input)
 {
     MemoryStream m = new MemoryStream();
     DeflaterOutputStream zipStream = new DeflaterOutputStream(m, new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(8));
     zipStream.Write(input, 0, input.Length);
     zipStream.Finish();
     return m.ToArray();
 }
Example #5
0
 internal static byte[] Deflate(byte[] buffer)
 {
     MemoryStream compressedBufferStream = new MemoryStream();
     DeflaterOutputStream deflaterStream = new DeflaterOutputStream(compressedBufferStream);
     deflaterStream.Write(buffer, 0, buffer.Length);
     deflaterStream.Close();
     return compressedBufferStream.ToArray();
 }
Example #6
0
 public static byte[] Compress(byte[] bytes)
 {
     MemoryStream memory = new MemoryStream();
     DeflaterOutputStream stream = new DeflaterOutputStream(memory, new Deflater(Deflater.BEST_COMPRESSION), 131072);
     stream.Write(bytes, 0, bytes.Length);
     stream.Close();
     return memory.ToArray();
 }
Example #7
0
 public static byte[] Compress(byte[] Data)
 {
     MemoryStream ms = new MemoryStream();
     Stream s = new DeflaterOutputStream(ms);
     s.Write(Data, 0, Data.Length);
     s.Close();
     return ms.ToArray();
 }
Example #8
0
 public byte[] Compress( byte[] bytes )
 {
     MemoryStream memory = new MemoryStream();
     Stream stream = new DeflaterOutputStream( memory,
         new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(
         ICSharpCode.SharpZipLib.Zip.Compression.Deflater.BEST_COMPRESSION ), 131072 );
     stream.Write( bytes, 0, bytes.Length );
     stream.Close();
     return memory.ToArray();
 }
Example #9
0
        public override byte[] Encode(byte[] data)
        {
            var o = new MemoryStream();

            var compressed = new DeflaterOutputStream(o, new Deflater(1));
            compressed.Write(data, 0, data.Length);
            compressed.Flush();
            compressed.Close();

            return o.ToArray();
        }
        public string Compress(string uncompressedString)
        {
            var stringAsBytes = Encoding.UTF8.GetBytes(uncompressedString);
            var ms = new MemoryStream();
            var outputStream = new DeflaterOutputStream(ms);
            outputStream.Write(stringAsBytes, 0, stringAsBytes.Length);
            outputStream.Close();
            var compressedData = ms.ToArray();

            return Convert.ToBase64String(compressedData, 0, compressedData.Length);
        }
Example #11
0
 /// <summary>
 /// Compress the specified data.
 /// </summary>
 /// <param name='data'>
 /// Data.
 /// </param>
 static string Compress(byte[] data)
 {
     MemoryStream ms = new MemoryStream();
     BinaryWriter bw = new BinaryWriter(ms);
     DeflaterOutputStream zs = new DeflaterOutputStream(ms);
     bw.Write(data.Length);
     zs.Write(data,0,data.Length);
     zs.Flush();
     zs.Close ();
     bw.Close();
     return "ZipStream:" + Convert.ToBase64String(ms.GetBuffer());
 }
Example #12
0
        /// <summary>
        /// Compress an array of bytes.
        /// </summary>
        /// <param name="_pBytes">An array of bytes to be compressed.</param>
        /// <returns>Compressed bytes.</returns>
        /// <example>
        /// Following example demonstrates the way of compressing an ASCII string text.
        /// <code>
        /// public void Compress()
        /// {
        ///     string source = "Hello, world!";
        ///     byte[] source_bytes = System.Text.Encoding.ASCII.GetBytes(source);
        ///     byte[] compressed = DataCompression.Compress(source_bytes);
        ///     
        ///     // Process the compressed bytes here.
        /// }
        /// </code>
        /// </example>
        /// <remarks>It is the best practice that use the overrided <b>DataCompression.Compress</b> method with <see cref="System.String"/> parameter to compress a string.</remarks>
        public static byte[] Compress(byte[] _pBytes)
        {
            MemoryStream ms = new MemoryStream();

            Deflater mDeflater = new Deflater(Deflater.BEST_COMPRESSION);
            DeflaterOutputStream outputStream = new DeflaterOutputStream(ms, mDeflater, 131072);

            outputStream.Write(_pBytes, 0, _pBytes.Length);
            outputStream.Close();

            return ms.ToArray();
        }
Example #13
0
		internal static Byte[] Deflate(Byte[] b)
		{
			System.IO.MemoryStream ms = new System.IO.MemoryStream();
			DeflaterOutputStream outStream =new DeflaterOutputStream( ms);
			
			outStream.Write(b, 0, b.Length);
			outStream.Flush();
			outStream.Finish();
			
			Byte[] result=ms.ToArray();
			outStream.Close();
			ms.Close();
			return result;
		}
Example #14
0
        public static byte[] Compress(byte[] data)
        {
            byte[] result = null;

            using (MemoryStream ms = new MemoryStream())
                using (Stream s = new DeflaterOutputStream(ms))
                {
                    s.Write(data, 0, data.Length);
                    s.Close();
                    result = ms.ToArray();
                }

            return result;
        }
Example #15
0
        public static void Serialize(Stream stream, PiaFile piaFile)
        {
            if (stream == null)
                throw new ArgumentNullException("Stream");

            if (piaFile == null)
                throw new ArgumentNullException("PiaFile");

            try
            {
                // Header
                var headerString = piaFile.Header.ToString();
                var headerBytes = Encoding.Default.GetBytes(headerString);
                stream.Write(headerBytes, 0, headerBytes.Length);

                // Nodes
                var nodeString = _serializeNode(piaFile);
                var nodeBytes = Encoding.Default.GetBytes(nodeString);

                // Deflation
                byte[] deflatedBytes;
                var deflater = new Deflater(Deflater.DEFAULT_COMPRESSION);
                using (var ms = new MemoryStream())
                {
                    var deflateStream = new DeflaterOutputStream(ms, deflater);
                    deflateStream.Write(nodeBytes, 0, nodeBytes.Length);
                    deflateStream.Finish();

                    deflatedBytes = ms.ToArray();
                }

                // Checksum
                var checkSum = new byte[12];
                BitConverter.GetBytes(deflater.Adler).CopyTo(checkSum, 0); // Adler
                BitConverter.GetBytes(nodeBytes.Length).CopyTo(checkSum, 4); // InflatedSize
                BitConverter.GetBytes(deflatedBytes.Length).CopyTo(checkSum, 8); // DeflatedSize
                stream.Write(checkSum, 0, checkSum.Length);

                // Final write
                stream.Write(deflatedBytes, 0, deflatedBytes.Length);
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #16
0
        public byte[] Compress(byte[] bytData)
        {
            try
            {
                var ms = new MemoryStream();
                var defl = new Deflater(9, false);
                Stream s = new DeflaterOutputStream(ms, defl);
                s.Write(bytData, 0, bytData.Length);
                s.Close();
                byte[] compressedData = ms.ToArray();
                return compressedData;
            }
            catch
            {

                throw;
            }
        }
Example #17
0
        /*
         * Name function: Compress
         * Purpose: compress a part of the byte array into a Zlib Block
         * Input: - buffer: byte array
         *        - offset: starting offset inside the array
         *        - count: num of bytes to compress starting from the offset
         * Output: compressed byte array block, the structure is:
         *         - magic word
         *         - max segment size
         *         - total compressed size
         *         - total uncompressed size
         *         - segment list
         *         - compressed data list
         */
        public static byte[] Compress(byte[] buffer, int offset, int count)
        {
            if(buffer == null)
                throw new ArgumentNullException();
            if (count < 0)
                throw new FormatException();
            if (offset + count > buffer.Length)
                throw new IndexOutOfRangeException();

            MemoryStream headBlock = new MemoryStream();
            MemoryStream dataBlock = new MemoryStream();
            DeflaterOutputStream zipStream;

            int numSeg = (int)Math.Ceiling((double)count / (double)maxSegmentSize);

            headBlock.WriteValueU32(magic);
            headBlock.WriteValueU32(maxSegmentSize);
            headBlock.WriteValueU32(0x0);            //total compressed size, still to calculate
            headBlock.WriteValueS32(count);          //total uncompressed size

            for (int i = count; i > 0; i -= (int)maxSegmentSize)
            {
                int copyBytes = Math.Min(i, (int)maxSegmentSize);
                uint precCompSize = (uint)dataBlock.Length;
                zipStream = new DeflaterOutputStream(dataBlock);
                zipStream.Write(buffer, offset + (count - i), copyBytes);
                zipStream.Flush();
                zipStream.Finish();
                headBlock.WriteValueU32((uint)dataBlock.Length - precCompSize); //compressed segment size
                headBlock.WriteValueS32(copyBytes); //uncompressed segment size
                //Console.WriteLine("  Segment size: {0}, total read: {1}, compr size: {2}", maxSegmentSize, copyBytes, (uint)dataBlock.Length - precCompSize);
            }

            headBlock.Seek(8, SeekOrigin.Begin);
            headBlock.WriteValueS32((int)dataBlock.Length); // total compressed size

            byte[] finalBlock = new byte[headBlock.Length + dataBlock.Length];
            Buffer.BlockCopy(headBlock.ToArray(), 0, finalBlock, 0, (int)headBlock.Length);
            Buffer.BlockCopy(dataBlock.ToArray(), 0, finalBlock, (int)headBlock.Length, (int)dataBlock.Length);
            headBlock.Close();
            dataBlock.Close();

            return finalBlock;
        }
    public static string Compress(byte[] data)
    {
        using(var m = new MemoryStream())
        {
            switch(technique)
            {
            case "ZipStream":

                var br = new BinaryWriter(m);
                var z = new DeflaterOutputStream(m);
                br.Write(data.Length);
                z.Write(data, 0, data.Length);
                z.Flush();
                z.Close();
                break;
            }
            return technique + ":" + Convert.ToBase64String(m.GetBuffer());
        }
    }
        public byte[] Deflate(string text)
        {
            var buffer = Encoding.UTF8.GetBytes(text);
            using (var ms = new MemoryStream())
            {
                using (var zipStream = new DeflaterOutputStream(ms, new Deflater(9)))
                {
                    zipStream.Write(buffer, 0, buffer.Length);
                    zipStream.Close();

                    var compressed = ms.ToArray();

                    var gzBuffer = new byte[compressed.Length + 4];
                    Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
                    Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);

                    return gzBuffer;
                }
            }
        }
        public static int Deflate(byte[] inBuffer, ref byte[] outBuffer)
        {
            int newLen = 0, flagOffset = 1;

            outBuffer[0] = inBuffer[0];
            if (inBuffer[0] == 0)
            {
                flagOffset = 2;
                outBuffer[1] = inBuffer[1];
            }

            if (inBuffer.Length > 30)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, false);
                    using (DeflaterOutputStream outStream = new DeflaterOutputStream(ms, deflater))
                    {
                        outStream.IsStreamOwner = false;
                        outStream.Write(inBuffer, flagOffset, inBuffer.Length - flagOffset);
                        outStream.Flush();
                        outStream.Finish();
                    }

                    ms.Position = 0;
                    ms.Read(outBuffer, flagOffset + 1, (int)ms.Length);
                    newLen = (int)ms.Length + flagOffset + 1;
                    outBuffer[flagOffset] = 0x5a;
                }
            }
            else
            {
                Buffer.BlockCopy(inBuffer, flagOffset, outBuffer, flagOffset + 1, inBuffer.Length - flagOffset);
                outBuffer[flagOffset] = 0xa5;
                newLen = inBuffer.Length + 1;
            }

            return newLen;
        }
	public static string Compress(byte[] data, ICodeProgress progress)
	{
		using(var m = new MemoryStream())
		{
			switch(technique)
			{
			case "ZipStream":
				
				var br = new BinaryWriter(m);
				var z = new DeflaterOutputStream(m);
				br.Write(data.Length);
				z.Write(data, 0, data.Length);
				z.Flush();
				z.Close();
				break;
			case "7Zip":
			default:
				return Convert.ToBase64String(SevenZipRadical.Compression.LZMA.SevenZipRadicalHelper.Compress(data, progress));
			}
			return technique + ":" + Convert.ToBase64String(m.GetBuffer());
		}
	}
Example #22
0
 /// <summary>
 /// ѹ�����ݣ����ѹ����ֵΪ-1��ʾ��������������ѹ������
 /// </summary>
 /// <param name="val">ԭʼ������</param>
 /// <returns>ѹ����������</returns>
 public byte[] Compress(byte[] val)
 {
     byte[] buf;
     if (overSize != -1 && val.Length > overSize) {
         using (MemoryStream destStream = new MemoryStream()) {
             Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
             using (DeflaterOutputStream compressStream = new DeflaterOutputStream(destStream, deflater)) {
                 compressStream.Write(val, 0, val.Length);
                 compressStream.Finish();
                 buf = new byte[destStream.Length + 1];
                 destStream.ToArray().CopyTo(buf, 1);
             }
             buf[0] = 1; // ��ѹ����־
             return buf;
         }
     }
     else {
         buf = new byte[val.Length + 1];
         val.CopyTo(buf, 1);
         buf[0] = 0; // δѹ����־
         return buf;
     }
 }
Example #23
0
        /// <summary>
        /// Compresses data using zlib.
        /// </summary>
        /// <param name="data">The data to compress</param>
        /// <returns>A byte array containing the compressed data</returns>
        public static byte[] Compress(string data)
        {
            // Commented out below as it loses extended ASCII (127+) and replaces with a ?
            // byte[] bytes = ASCIIEncoding.ASCII.GetBytes(data);

            // Encoding using default terminal extended ascii codepage 437
            byte[] bytes = Encoding.GetEncoding(437).GetBytes(data);
            byte[] returnBytes;
            using (var stream = new MemoryStream())
            {
                using (var compressedStream = new DeflaterOutputStream(stream))
                {
                    compressedStream.Write(bytes, 0, bytes.Length);
                    compressedStream.Finish();
                    stream.Position = 0;

                    returnBytes = new byte[stream.Length];
                    stream.Read(returnBytes, 0, returnBytes.Length);
                }
            }

            return returnBytes;
        }
Example #24
0
        public static byte[] Compress( byte []b, int offset, int len )
        {
            try
            {
                /*zLib e = new zLib();
                byte []compressedData = null;
                e.CompressStream( b, ref compressedData );*/

                MemoryStream ms = new MemoryStream();
                DeflaterOutputStream defl = new DeflaterOutputStream( ms );

                defl.Write(b, offset, len );
                defl.Flush();
                defl.Close();
                byte[] compressedData = (byte[])ms.ToArray();
                //HexViewer.View( compressedData, 0, compressedData.Length );
                return compressedData;
            }
            catch(Exception e)
            {
                Console.WriteLine( e.Message );
                return null;
            }
        }
Example #25
0
 public static string Compress(byte[] data)
 {
     string result;
     using (MemoryStream memoryStream = new MemoryStream())
     {
         string text = CompressionHelper.technique;
         if (text != null)
         {
             if (CompressionHelper.<>f__switch$map1F == null)
             {
                 CompressionHelper.<>f__switch$map1F = new Dictionary<string, int>(1)
                 {
                     {
                         "ZipStream",
                         0
                     }
                 };
             }
             int num;
             if (CompressionHelper.<>f__switch$map1F.TryGetValue(text, out num))
             {
                 if (num == 0)
                 {
                     BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
                     DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(memoryStream);
                     binaryWriter.Write(data.Length);
                     deflaterOutputStream.Write(data, 0, data.Length);
                     deflaterOutputStream.Flush();
                     deflaterOutputStream.Close();
                 }
             }
         }
         result = CompressionHelper.technique + ":" + Convert.ToBase64String(memoryStream.GetBuffer());
     }
     return result;
 }
Example #26
0
		/// <summary>
		/// deflates (zlib) a VideoCopy, returning a byte array suitable for insertion into a JMD file
		/// the byte array includes width and height dimensions at the beginning
		/// this is run asynchronously for speedup, as compressing can be slow
		/// </summary>
		/// <param name="v">video frame to compress</param>
		/// <returns>zlib compressed frame, with width and height prepended</returns>
		byte[] GzipFrame(VideoCopy v)
		{
			MemoryStream m = new MemoryStream();
			// write frame height and width first
			m.WriteByte((byte)(v.BufferWidth >> 8));
			m.WriteByte((byte)(v.BufferWidth & 255));
			m.WriteByte((byte)(v.BufferHeight >> 8));
			m.WriteByte((byte)(v.BufferHeight & 255));
			var g = new DeflaterOutputStream(m, new Deflater(token.compressionlevel));
			g.IsStreamOwner = false; // leave memory stream open so we can pick its contents
			g.Write(v.VideoBuffer, 0, v.VideoBuffer.Length);
			g.Flush();
			g.Close();
			byte[] ret = m.GetBuffer();
			Array.Resize(ref ret, (int)m.Length);
			m.Close();
			return ret;
		}
Example #27
0
        internal byte[] WriteSwf(object data, bool debug, CompressionLevels compressionLevel, string url, bool allowDomain)
        {
            // Create the SWF
            byte headerType = compressionLevel != CompressionLevels.None ? SwxAssembler.CompressedSwf : SwxAssembler.UncompressedSwf;

            _swf.Put(headerType);
            _swf.Put(SwxAssembler.SwfHeader);

            //DoAction
            _swf.Put(SwxAssembler.ActionDoAction);
            int doActionBlockSizeIndex = (int)_swf.Position;

            _swf.Skip(4);
            int doActionBlockStartIndex = (int)_swf.Position;

            if (debug)
            {
                _swf.Put(SwxAssembler.DebugStart);
            }

            _swf.Put(SwxAssembler.ActionPushData);
            _swf.Mark();  //start marking for length check
            _swf.Skip(2); //Skip ActionRecord length

            // Add the 'result' variable name -- either
            // using the constant table if in debug mode
            // or as a regular string otherwise
            if (debug)
            {
                _swf.Put(SwxAssembler.DataTypeConstantPool1);
                _swf.Put((byte)0);
            }
            else
            {
                PushString("result");
            }
            DataToBytecode(data);
            //Put ActionRecord length
            EndPush();

            _swf.Put(SwxAssembler.ActionSetVariable);
            if (allowDomain)
            {
                GenerateAllowDomainBytecode(url);
            }
            if (debug)
            {
                _swf.Put(SwxAssembler.DebugEnd);
            }

            //Fix DoAction size
            long   doActionBlockEndIndex    = _swf.Position;
            UInt32 doActionBlockSizeInBytes = (UInt32)(doActionBlockEndIndex - doActionBlockStartIndex);

            _swf.Put(doActionBlockSizeIndex, doActionBlockSizeInBytes);

            //Swf End
            _swf.Put(SwxAssembler.ActionShowFrame);
            _swf.Put(SwxAssembler.ActionEndSwf);

            //Fix Swf size
            UInt32 swfSizeInBytes = (UInt32)_swf.Length;

            _swf.Put(4, swfSizeInBytes);

            _swf.Flip();
            byte[] buffer = _swf.ToArray();

            if (compressionLevel != CompressionLevels.None)
            {
                MemoryStream msCompressed = new MemoryStream();
#if (NET_1_1)
                ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream deflaterOutputStream = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(msCompressed, new ICSharpCode.SharpZipLib.Zip.Compression.Deflater((int)compressionLevel, false));
                deflaterOutputStream.Write(buffer, 8, buffer.Length - 8);
                deflaterOutputStream.Close();
#else
                DeflateStream deflateStream = new DeflateStream(msCompressed, CompressionMode.Compress, false);
                deflateStream.Write(buffer, 8, buffer.Length - 8);
                deflateStream.Close();
#endif
                byte[] msBuffer         = msCompressed.ToArray();
                byte[] compressedBuffer = new byte[msBuffer.Length + 8];
                Buffer.BlockCopy(buffer, 0, compressedBuffer, 0, 8);
                Buffer.BlockCopy(msBuffer, 0, compressedBuffer, 8, msBuffer.Length);
                buffer = compressedBuffer;
            }
            //ByteBuffer dumpBuffer = ByteBuffer.Wrap(buffer);
            //dumpBuffer.Dump("test.swf");
            return(buffer);
        }
        /// <summary>
        /// see <see cref="SwfDotNet.IO.Tags.BaseTag">base class</see>
        /// </summary>
        public override void UpdateData(byte version)
        {
            if (version < 2)
                return;

            // Compression process
            int lenghtOfCompressedBlock = 0;
            byte[] compressArray = null;
            MemoryStream unCompressedStream = new MemoryStream();
            BufferedBinaryWriter unCompressedWriter = new BufferedBinaryWriter(unCompressedStream);

            if (this._bitmapFormat == 3)
            {
                this._colorMapData.WriteTo(unCompressedWriter);
            }
            else if (this._bitmapFormat == 4 || this._bitmapFormat == 5)
            {
                this._bitmapColorData.WriteTo(unCompressedWriter);
            }

            MemoryStream compressedStream = new MemoryStream();
            DeflaterOutputStream ouput = new DeflaterOutputStream(compressedStream);
            byte[] unCompressArray = unCompressedStream.ToArray();
            ouput.Write(unCompressArray, 0, unCompressArray.Length);
            ouput.Finish();
            compressArray = compressedStream.ToArray();
            lenghtOfCompressedBlock = compressArray.Length;
            ouput.Close();
            unCompressedStream.Close();

            //Writing process
            MemoryStream m = new MemoryStream();
            BufferedBinaryWriter w = new BufferedBinaryWriter(m);

            RecordHeader rh = new RecordHeader(TagCode, GetSizeOf(lenghtOfCompressedBlock));

            rh.WriteTo(w);
            w.Write(this._characterId);
            w.Write(this._bitmapFormat);
            w.Write(this._bitmapWidth);
            w.Write(this._bitmapHeight);

            if (this._bitmapFormat == 3)
            {
                w.Write(this._bitmapColorTableSize);
                w.Write(compressArray);
            }
            else if (this._bitmapFormat == 4 || this._bitmapFormat == 5)
            {
                w.Write(compressArray);
            }

            w.Flush();
            // write to data array
            _data = m.ToArray();
        }
        private void PurgeModernWithCompression()
        {
            int packetLength = 0; // -- data.Length + GetVarIntBytes(data.Length).Length
            int dataLength = 0; // -- UncompressedData.Length
            var data = _buffer;

            packetLength = _buffer.Length + GetVarIntBytes(_buffer.Length).Length; // -- Get first Packet length

            if (packetLength >= ModernCompressionThreshold) // -- if Packet length > threshold, compress
            {
                using (var outputStream = new MemoryStream())
                using (var inputStream = new DeflaterOutputStream(outputStream, new Deflater(0)))
                {
                    inputStream.Write(_buffer, 0, _buffer.Length);
                    inputStream.Close();

                    data = outputStream.ToArray();
                }

                dataLength = data.Length;
                packetLength = dataLength + GetVarIntBytes(data.Length).Length; // -- Calculate new packet length
            }


            var packetLengthByteLength = GetVarIntBytes(packetLength);
            var dataLengthByteLength = GetVarIntBytes(dataLength);

            var tempBuf = new byte[data.Length + packetLengthByteLength.Length + dataLengthByteLength.Length];

            Buffer.BlockCopy(packetLengthByteLength, 0, tempBuf, 0, packetLengthByteLength.Length);
            Buffer.BlockCopy(dataLengthByteLength, 0, tempBuf, packetLengthByteLength.Length, dataLengthByteLength.Length);
            Buffer.BlockCopy(data, 0, tempBuf, packetLengthByteLength.Length + dataLengthByteLength.Length, data.Length);

            if (EncryptionEnabled)
                _aesStream.Write(tempBuf, 0, tempBuf.Length);
            else
                _stream.Write(tempBuf, 0, tempBuf.Length);

            _buffer = null;
        }
        private IAsyncResult BeginWriteWithCompression(byte[] data, AsyncCallback callback, object state)
        {
            int dataLength = 0; // UncompressedData.Length

            // -- data here is raw IPacket with Packet length.
            using (var reader = new MinecraftDataReader(data, Mode))
            {
                var packetLength = reader.ReadVarInt();
                var packetLengthByteLength1 = GetVarIntBytes(packetLength).Length; // -- Getting size of Packet Length

                var tempBuf1 = new byte[data.Length - packetLengthByteLength1];
                Buffer.BlockCopy(data, packetLengthByteLength1, tempBuf1, 0, tempBuf1.Length); // -- Creating data without Packet Length

                packetLength = tempBuf1.Length + GetVarIntBytes(tempBuf1.Length).Length; // -- Get first Packet length

                // -- Handling this data like normal
                if (packetLength >= ModernCompressionThreshold) // if Packet length > threshold, compress
                {
                    using (var outputStream = new MemoryStream())
                    using (var inputStream = new DeflaterOutputStream(outputStream, new Deflater(0)))
                    {
                        inputStream.Write(tempBuf1, 0, tempBuf1.Length);
                        inputStream.Close();

                        tempBuf1 = outputStream.ToArray();
                    }

                    dataLength = tempBuf1.Length;
                    packetLength = dataLength + GetVarIntBytes(tempBuf1.Length).Length; // calculate new packet length
                }


                var packetLengthByteLength = GetVarIntBytes(packetLength);
                var dataLengthByteLength = GetVarIntBytes(dataLength);

                var tempBuf2 = new byte[tempBuf1.Length + packetLengthByteLength.Length + dataLengthByteLength.Length];

                Buffer.BlockCopy(packetLengthByteLength, 0, tempBuf2, 0                                                          , packetLengthByteLength.Length);
                Buffer.BlockCopy(dataLengthByteLength  , 0, tempBuf2, packetLengthByteLength.Length                              , dataLengthByteLength.Length);
                Buffer.BlockCopy(tempBuf1              , 0, tempBuf2, packetLengthByteLength.Length + dataLengthByteLength.Length, tempBuf1.Length);

                if (EncryptionEnabled)
                    return _aesStream.BeginWrite(tempBuf2, 0, tempBuf2.Length, callback, state);
                else
                    return _stream.BeginWrite(tempBuf2, 0, tempBuf2.Length, callback, state);
            }
        }
		MemoryStream Deflate(byte[] data, int level, bool zlib)
		{
			MemoryStream memoryStream = new MemoryStream();
			
			Deflater deflater = new Deflater(level, !zlib);
			using ( DeflaterOutputStream outStream = new DeflaterOutputStream(memoryStream, deflater) )
			{
				outStream.IsStreamOwner = false;
				outStream.Write(data, 0, data.Length);
				outStream.Flush();
				outStream.Finish();
			}
			return memoryStream;
		}