コード例 #1
0
        public virtual int ZipCompress(Stream uncompressed, Stream compressed)
        {
            uncompressed.Seek(0, SeekOrigin.Begin);
            DeflaterOutputStream
                zipStream =
                new DeflaterOutputStream(compressed);

            zipStream.IsStreamOwner = false; // compress wants to have compressed Stream open

            int bufferSize = 1024 * 8;

            byte[] buffer = new byte[bufferSize];
            int    readByte = 0; int position = 0;
            long   length = uncompressed.Length;

            while (position < length - 1)
            {
                readByte = uncompressed.Read(buffer, 0, bufferSize);
                zipStream.Write(buffer, 0, readByte);
                position += readByte;
            }


            zipStream.Finish();
            zipStream.Flush();
            int result = (int)compressed.Length;

            zipStream.Close();
            return(result);
        }
コード例 #2
0
ファイル: defcomp.cs プロジェクト: Eisai/pragmasql
		// 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;
		}
コード例 #3
0
ファイル: ZLib.cs プロジェクト: BGCX261/zpoc3-svn-to-git
 public byte[] close()
 {
     zlibstream.Finish();
     byte[] test = Read();
     zlibstream.Close();
     return(test);
 }
コード例 #4
0
        /// <summary>
        /// Compressed data using the zlib compression library.
        /// </summary>
        /// <param name="data">Data to be compressed.</param>
        /// <param name="gnf">GNF class that is associated with that data.</param>
        /// <returns>Compressed data</returns>
        private static byte[] GetCompressedZlibData(byte[] data, GNF gnf)
        {
            if (data == null || data.Length == 0)
            {
                return(data);
            }

            using (var inStream = new MemoryStream(data))
            {
                var outStream      = new MemoryStream();
                var compressStream = new DeflaterOutputStream(outStream, new Deflater(Deflater.DEFAULT_COMPRESSION));

                int bufferSize;
                var buffer = new byte[4096];

                while ((bufferSize = inStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    compressStream.Write(buffer, 0, bufferSize);
                }

                compressStream.Close();
                byte[] outStreamData = outStream.ToArray();

                gnf.Size = (uint)outStreamData.Length;
                return(outStreamData);
            }
        }
コード例 #5
0
ファイル: DataOper.cs プロジェクト: HX-Hendrix/Shbo.Tools
        /// <summary>
        /// 压缩字符串数据
        /// </summary>
        /// <param name="data">压缩字符串</param>
        /// <param name="result">返回压缩内容</param>
        /// <returns></returns>
        public static bool Compress(string data, ref string result)
        {
            try
            {
                byte[] buffer;
                using (MemoryStream ms = new MemoryStream())
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(ms, data);
                    buffer = ms.ToArray();
                    ms.Close();
                    ms.Dispose();
                }

                using (MemoryStream msout = new MemoryStream())
                {
                    Deflater defl = new Deflater();
                    using (DeflaterOutputStream mem1 = new DeflaterOutputStream(msout, defl))
                    {
                        mem1.Write(buffer, 0, buffer.Length);
                        mem1.Close();
                        mem1.Dispose();
                    }
                    result = Convert.ToBase64String(msout.ToArray());
                    msout.Close();
                    msout.Dispose();
                }
                return(true);
            }
            catch (Exception ex)
            {
                result = ex.Message;
                return(false);
            }
        }
コード例 #6
0
ファイル: EscherMetafileBlip.cs プロジェクト: IMULMUL/npoi
        public void SetPictureData(byte[] pictureData)
        {
            base.PictureData = (pictureData);
            UncompressedSize = (pictureData.Length);

            // info of chicago project:
            // "... LZ compression algorithm in the format used by GNU Zip deflate/inflate with a 32k window ..."
            // not sure what to do, when lookup tables exceed 32k ...

            try
            {
                MemoryStream         bos = new MemoryStream();
                DeflaterOutputStream dos = new DeflaterOutputStream(bos);
                dos.Write(pictureData, 0, pictureData.Length);
                dos.Close();
                raw_pictureData = bos.ToArray();
            }
            catch (IOException e)
            {
                throw new RuntimeException("Can't compress metafile picture data", e);
            }

            CompressedSize = (raw_pictureData.Length);
            IsCompressed   = (true);
        }
コード例 #7
0
ファイル: Wrapper.cs プロジェクト: hashem30/Study
        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;
            }
        }
コード例 #8
0
        public static string Compress(string sBuffer)
        {
            byte[] compressed     = null;
            string compressedText = null;

            try {
                byte[] bytesBuffer = Encoding.UTF8.GetBytes(sBuffer);

                using (MemoryStream compressStream = new MemoryStream()) {
                    using (DeflaterOutputStream defStream = new DeflaterOutputStream(compressStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true))) {
                        defStream.Write(bytesBuffer, 0, bytesBuffer.Length);
                        defStream.Flush();
                        defStream.Close();

                        compressed = compressStream.ToArray();
                    }
                }
            } catch (Exception ex) {
                ConsoleEx.DebugLog("Deflater compress error : " + ex.ToString());
            } finally {
                if (compressed != null)
                {
                    compressedText = Convert.ToBase64String(compressed);
                }
            }

            return(compressedText);
        }
コード例 #9
0
        /// <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();
        }
コード例 #10
0
        /// <summary>
        /// Compresses the data at the current read position in the source stream to the specified targetstream.
        /// </summary>
        /// <param name="sourceStream">The stream containing the data to be compressed.</param>
        /// <param name="targetStream">The stream that will receive the compressed data.</param>
        /// <param name="count">The number of bytes to compress.</param>
        /// <param name="closeStream">Close the source stream after compression.</param>
        public static void Compress(Stream sourceStream, Stream targetStream, long count, bool closeStream)
        {
            if (sourceStream == null)
            {
                throw new ArgumentNullException(nameof(sourceStream));
            }

            if (targetStream == null)
            {
                throw new ArgumentNullException(nameof(targetStream));
            }

            var compressStream = new DeflaterOutputStream(targetStream)
            {
                IsStreamOwner = false,
            };

            if (count > 0)
            {
                sourceStream.CopyBlocksTo(compressStream, count);
            }
            else
            {
                sourceStream.CopyBlocksTo(compressStream);
            }

            compressStream.Finish();
            if (closeStream)
            {
#if !NETSTANDARD13
                compressStream.Close();
                sourceStream.Close();
#endif
            }
        }
コード例 #11
0
ファイル: EscherBlipWMFRecord.cs プロジェクト: purehzj/npoi-1
 /// <summary>
 /// Compress the contents of the provided array
 /// </summary>
 /// <param name="data">An uncompressed byte array</param>
 /// <returns></returns>
 public static byte[] Compress(byte[] data)
 {
     using (MemoryStream out1 = new MemoryStream())
     {
         Deflater             deflater             = new Deflater(0, false);
         DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(out1, deflater);
         try
         {
             //for (int i = 0; i < data.Length; i++)
             //deflaterOutputStream.WriteByte(data[i]);
             deflaterOutputStream.Write(data, 0, data.Length);   //Tony Qu changed the code
             return(out1.ToArray());
         }
         catch (IOException e)
         {
             throw new RecordFormatException(e.ToString());
         }
         finally
         {
             out1.Close();
             if (deflaterOutputStream != null)
             {
                 deflaterOutputStream.Close();
             }
         }
     }
 }
コード例 #12
0
        public void DeflatorStreamOwnership()
        {
            var memStream = new TrackedMemoryStream();
            var s         = new DeflaterOutputStream(memStream);

            Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
            Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");

            s.Close();

            Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close");
            Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close");

            memStream = new TrackedMemoryStream();
            s         = new DeflaterOutputStream(memStream);

            Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially");
            Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially");

            s.IsStreamOwner = false;
            s.Close();

            Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close");
            Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close");
        }
コード例 #13
0
        private static byte[] getOutputByCompress(byte[] toByteArray)
        {
            int unCompressedLength = 0;
            int compressedLength   = 0;

            byte[] input = toByteArray;
            unCompressedLength = input.Length;

            MemoryStream         memoryStream = new MemoryStream();
            Deflater             compressor   = new Deflater();
            DeflaterOutputStream defos        = new DeflaterOutputStream(memoryStream, compressor);

            defos.Write(input, 0, input.Length);
            defos.Flush();
            defos.Finish();
            byte[] output = memoryStream.ToArray();
            compressedLength = output.Length;

            memoryStream.Close();
            defos.Close();

            //set compress flag and compressedLength, unCompressedLength
            byte[] sendData = new byte[output.Length + TransferUtil.getLengthOfByte() + TransferUtil.getLengthOfInt() + TransferUtil.getLengthOfInt()];
            sendData[0] = TransferObject.COMPRESS_FLAG; //0:normal; 1:compress
            TransferOutputStream fos = new TransferOutputStream(sendData);

            fos.skipAByte();
            fos.writeInt(unCompressedLength);
            fos.writeInt(compressedLength);
            Array.Copy(output, 0, sendData, TransferUtil.getLengthOfByte() + TransferUtil.getLengthOfInt() + TransferUtil.getLengthOfInt(), output.Length);

            return(sendData);
        }
コード例 #14
0
 public static void Compress(Stream stream, byte[] input)
 {
     using (var zlib = new DeflaterOutputStream(stream)) {
         zlib.IsStreamOwner = false;
         zlib.Write(input, 0, input.Length);
         zlib.Flush();
         zlib.Close();
     }
 }
コード例 #15
0
ファイル: ZipUtility.cs プロジェクト: shdwdln/FtexTool
        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());
        }
コード例 #16
0
ファイル: Compression.cs プロジェクト: natedahl32/mClient
        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());
        }
コード例 #17
0
ファイル: Milo.cs プロジェクト: zurgeg/riivolution
        private int DeflateStream(Stream i, Stream o)
        {
            DeflaterOutputStream def = new DeflaterOutputStream(o, new Deflater(9, true), 0x400);
            int ret = (int)Util.StreamCopy(def, i);

            def.IsStreamOwner = false;
            def.Close();
            return(ret);
        }
コード例 #18
0
 public static byte[] Compress(byte[] bytes)
 {
     using var decompressedStream = new MemoryStream(bytes);
     using var resultStream       = new MemoryStream();
     using var compressionStream  = new DeflaterOutputStream(resultStream);
     decompressedStream.CopyTo(compressionStream);
     compressionStream.Close();
     return(resultStream.ToArray());
 }
コード例 #19
0
        static int Compress(string file, string zipFile)
        {
            //var fstowrite = new FileStream(zipFile, FileMode.Create, FileAccess.Write);
            //System.IO.Compression.DeflateStream ds = new System.IO.Compression.DeflateStream(fstowrite, System.IO.Compression.CompressionMode.Compress, leaveOpen: true);
            //using (var ss = new FileStream(file, FileMode.Open, FileAccess.Read))
            //{
            //    ss.CopyTo(ds);
            //    //Console.WriteLine();
            //    //len2 = (int)ds.Length;
            //}

            //ds.Close();
            //ds.Dispose();
            //var len = fstowrite.Length;
            //fstowrite.Close();
            //fstowrite.Dispose();
            //int len2 = (int)len;
            //return len2;

            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 ICSharpCode.SharpZipLib.Zip.Compression.Deflater(ICSharpCode.SharpZipLib.Zip.Compression.Deflater.DEFAULT_COMPRESSION, false));
                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((int)length);
        }
        private byte[] CompressBinary(byte[] input)
        {
            var inputBuffer  = new MemoryStream(input, 0, input.Length);
            var outputBuffer = new MemoryStream();
            var compressor   = new DeflaterOutputStream(outputBuffer, new Deflater(Deflater.BEST_COMPRESSION, false));

            StreamUtils.PumpStream(inputBuffer, compressor);
            inputBuffer.Close();
            compressor.Close();
            return(outputBuffer.ToArray());
        }
コード例 #21
0
 public static byte[] Compress(byte[] input)
 {
     using (var mem = new MemoryStream()) {
         using (var zlib = new DeflaterOutputStream(mem)) {
             zlib.Write(input, 0, input.Length);
             zlib.Flush();
             zlib.Close();
             return(mem.ToArray());
         }
     }
 }
コード例 #22
0
 /// <summary>
 /// 压缩原字节数组到字节数组
 /// </summary>
 /// <param name="source">原字节数组</param>
 /// <returns>字节数组</returns>
 public static byte[] Compress(byte[] source)
 {
     using (MemoryStream mMemory = new MemoryStream())
     {
         Deflater             mDeflater = new Deflater(Deflater.BEST_COMPRESSION);
         DeflaterOutputStream mStream   = new DeflaterOutputStream(mMemory, mDeflater, 131072);
         mStream.Write(source, 0, source.Length);
         mStream.Close();
         return(mMemory.ToArray());
     }
 }
コード例 #23
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());
        }
コード例 #24
0
        /// <summary>
        /// Compresses a stream using zlib.
        /// </summary>
        /// <param name="stream">Original Stream</param>
        /// <param name="CompressionLevel">Compression level for zlib</param>
        /// <returns>zlib-compressed byte array</returns>
        public byte[] Compress(Stream stream, int CompressionLevel)
        {
            using var memoryStream   = new MemoryStream();
            using var deflaterStream = new DeflaterOutputStream(memoryStream, new Deflater(CompressionLevel));

            //write input stream to the deflater stream
            stream.Position = 0;
            stream.CopyTo(deflaterStream);
            deflaterStream.Close();

            return(memoryStream.ToArray());
        }
コード例 #25
0
ファイル: SWFWriter.cs プロジェクト: mkbiltek2019/Swiffotron
        /// <summary>
        /// Takes a SWF object and turns it into a .swf binary file. It might seem nicer to
        /// write it to a stream, but the stream has a file length at the start which we only
        /// know once we've written it all out to a byte array anyway. Returning it as a
        /// chunk of data is simply more honest; an output stream would promise streaminess behind
        /// the scenes that we cannot deliver.
        /// </summary>
        /// <returns>The .swf data is returned as a byte array.</returns>
        public byte[] ToByteArray()
        {
            /* We start writing things mid-way through the header, at the point
             * where compression comes into effect. Once we've created and perhaps
             * compressed the data, we can write the first part of the header and
             * concatenate the rest. */

            writtenJPEGTable = null;

            /* The file contains tags, which can contain tags, each of which is prefixed with a length.
             * To track all this, we use a stack of writers, each with its own buffer. The first on the
             * stack is the buffer that will contain the file itself. */
            this.writers = new Stack <WriteBuffer>();
            this.swfOut  = new WriteBuffer(Tag.None, "swf");
            this.writers.Push(this.swfOut);

            this.swfOut.WriteRect(new Rect(0, this.swf.FrameWidth, 0, this.swf.FrameHeight));

            this.swfOut.WriteFIXED8(this.swf.Fps);
            this.swfOut.WriteUI16(this.swf.FrameCount);

            this.WriteTags();

            /* Ok, we basically have a SWF now. All we need to do is compress it and
             * stick a header on at the front... */

            byte[] body    = this.swfOut.Data;
            uint   fileLen = (uint)(body.Length + 8); /* Add the 8 bytes of header we haven't done yet. */

            if (this.options.Compressed)
            {
                MemoryStream         zbytes = new MemoryStream();
                DeflaterOutputStream zos    = new DeflaterOutputStream(zbytes);
                zos.Write(body, 0, body.Length);
                zos.Close();
                body = zbytes.ToArray();
            }

            MemoryStream      final       = new MemoryStream();
            SWFDataTypeWriter finalWriter = new SWFDataTypeWriter(final);

            finalWriter.WriteUI24(this.options.Compressed ? SIG_COMPRESSED : SIG_UNCOMPRESSED);

            /* ISSUE 27: Hard-coded SWF version 10. Technically this should be an option but
             * for now we don't want the headache of version-specific code. */
            finalWriter.WriteUI8(SWF_VERSION);

            finalWriter.WriteUI32(fileLen);

            finalWriter.Write(body, 0, body.Length);

            return(final.ToArray());
        }
コード例 #26
0
        public static byte[] Compress(byte[] rawContent)
        {
            MemoryStream destinationStream = new MemoryStream();

            DeflaterOutputStream outputStream = new DeflaterOutputStream(destinationStream);

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

            byte[] compressedBytes = destinationStream.ToArray();
            destinationStream.Close();
            return(compressedBytes);
        }
コード例 #27
0
ファイル: SharpZipLibHelp.cs プロジェクト: Souing/CodeBak
        /// <summary>
        /// 压缩
        /// add by zhuzhijia
        /// </summary>
        /// <param name="pBytes">byte数组</param>
        /// <returns>byte数组</returns>
        private static byte[] Compress(byte[] pBytes)
        {
            MemoryStream mMemory = new MemoryStream();

            Deflater mDeflater = new Deflater(Deflater.BEST_COMPRESSION);
            //DeflaterOutputStream mStream = new DeflaterOutputStream( mMemory,mDeflater,131072 );
            DeflaterOutputStream mStream = new DeflaterOutputStream(mMemory, mDeflater);

            mStream.Write(pBytes, 0, pBytes.Length);
            mStream.Close();

            return(mMemory.ToArray());
        }
コード例 #28
0
        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));
                }
            }
        }
コード例 #29
0
        public static byte[] ZipBytes(byte[] input)
        {
            MemoryStream ms     = new MemoryStream();
            Deflater     zipper = new Deflater();

            zipper.SetLevel(5);
            Stream st = new DeflaterOutputStream(ms, zipper);

            st.Write(input, 0, input.Length);
            st.Flush();
            st.Close();
            byte[] result = (byte[])ms.ToArray();
            return(result);
        }
コード例 #30
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);
        }