Exemplo n.º 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;

            }
        }
		// 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;
		}
Exemplo n.º 3
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();
 }
Exemplo n.º 4
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();
 }
Exemplo n.º 5
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();
 }
Exemplo n.º 6
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();
 }
Exemplo n.º 7
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);
        }
Exemplo n.º 9
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();
        }
Exemplo n.º 10
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;
        }
Exemplo n.º 11
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;
		}
Exemplo n.º 12
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;
            }
        }
Exemplo n.º 13
0
    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;
                }
            }
        }
Exemplo n.º 15
0
	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());
		}
	}
Exemplo n.º 16
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;
 }
Exemplo n.º 17
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;
            }
        }
Exemplo n.º 18
0
 /// <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();
             }
         }
     }
 }
Exemplo n.º 19
0
        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;
        }
        public void SaveTo(string filePath)
        {
            using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
            {

                using (XmlTextWriter writer = new XmlTextWriter(fileStream, Encoding.UTF8))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartDocument();

                    writer.WriteDocType("plist", "-//Apple//DTD PLIST 1.0//EN", "http://www.apple.com/DTDs/PropertyList-1.0.dtd", null);
                    writer.WriteStartElement("plist");
                    writer.WriteAttributeString("version", "1.0");
                    writer.WriteStartElement("dict");

                    WriteFloat(writer, "angle", Angle);
                    WriteFloat(writer, "angleVariance", AngleVar);

                    WriteInt(writer, "blendFuncDestination", (int)DestBlendFunc);
                    WriteInt(writer, "blendFuncSource", (int)SrcBlendFunc);

                    WriteFloat(writer, "duration", Duration);
                    WriteFloat(writer, "emitterType", (float)Mode);
                    WriteFloat(writer, "emissionRate", EmissionRate);

                    WriteFloat(writer, "finishColorAlpha", EndColor.A / 255.0f);
                    WriteFloat(writer, "finishColorBlue", EndColor.B / 255.0f);
                    WriteFloat(writer, "finishColorGreen", EndColor.G / 255.0f);
                    WriteFloat(writer, "finishColorRed", EndColor.R / 255.0f);

                    WriteFloat(writer, "finishColorVarianceAlpha", EndColorVar.A / 255.0f);
                    WriteFloat(writer, "finishColorVarianceBlue", EndColorVar.B / 255.0f);
                    WriteFloat(writer, "finishColorVarianceGreen", EndColorVar.G / 255.0f);
                    WriteFloat(writer, "finishColorVarianceRed", EndColorVar.R / 255.0f);

                    WriteFloat(writer, "rotationStart", StartSpin);
                    WriteFloat(writer, "rotationStartVariance", StartSpinVar);
                    WriteFloat(writer, "rotationEnd", EndSpin);
                    WriteFloat(writer, "rotationEndVariance", EndSpinVar);

                    WriteFloat(writer, "finishParticleSize", EndSize);
                    WriteFloat(writer, "finishParticleSizeVariance", EndSizeVar);

                    WriteFloat(writer, "gravityx", GravityX);
                    WriteFloat(writer, "gravityy", GravityY);
                    WriteFloat(writer, "maxParticles", TotalParticles);

                    WriteFloat(writer, "maxRadius", StartRadius);
                    WriteFloat(writer, "maxRadiusVariance", StartRadiusVar);
                    WriteFloat(writer, "minRadius", EndRadius);
                    WriteFloat(writer, "minRadiusVariance", EndRadiusVar);

                    WriteFloat(writer, "particleLifespan", Life);
                    WriteFloat(writer, "particleLifespanVariance", LifeVar);

                    WriteFloat(writer, "radialAccelVariance", RadialAccelVar);
                    WriteFloat(writer, "radialAcceleration", RadialAccel);

                    WriteFloat(writer, "rotatePerSecond", RotatePerSecond);
                    WriteFloat(writer, "rotatePerSecondVariance", RotatePerSecondVar);

                    WriteFloat(writer, "sourcePositionVariancex", PosVarX);
                    WriteFloat(writer, "sourcePositionVariancey", PosVarY);

                    WriteFloat(writer, "sourcePositionx", SourcePositionX);
                    WriteFloat(writer, "sourcePositiony", SourcePositionY);

                    WriteFloat(writer, "speed", Speed);
                    WriteFloat(writer, "speedVariance", SpeedVar);

                    WriteFloat(writer, "startColorAlpha", StartColor.A / 255.0f);
                    WriteFloat(writer, "startColorBlue", StartColor.B / 255.0f);
                    WriteFloat(writer, "startColorGreen", StartColor.G / 255.0f);
                    WriteFloat(writer, "startColorRed", StartColor.R / 255.0f);

                    WriteFloat(writer, "startColorVarianceAlpha", StartColorVar.A / 255.0f);
                    WriteFloat(writer, "startColorVarianceBlue", StartColorVar.B / 255.0f);
                    WriteFloat(writer, "startColorVarianceGreen", StartColorVar.G / 255.0f);
                    WriteFloat(writer, "startColorVarianceRed", StartColorVar.R / 255.0f);

                    WriteFloat(writer, "startParticleSize", StartSize);
                    WriteFloat(writer, "startParticleSizeVariance", StartSizeVar);

                    WriteFloat(writer, "tangentialAccelVariance", TangentialAccelVar);
                    WriteFloat(writer, "tangentialAcceleration", TangentialAccel);

                    WriteString(writer, "textureFileName", TexturePath);

                    if (IsSaveTextureImageData)
                    {
                        if (string.IsNullOrEmpty(TextureImageData))
                        {
                            if (File.Exists(TexturePath))
                            {
                                var data=File.ReadAllBytes(TexturePath);
                                MemoryStream ms=new MemoryStream();
                                DeflaterOutputStream outputStream = new DeflaterOutputStream(ms);
                                outputStream.Write(data,0,data.Length);
                                outputStream.Close();
                                data = ms.ToArray();

                                TextureImageData = Convert.ToBase64String(data);
                            }
                        }

                        if (TextureImageData.Length > 0)
                        {
                            WriteString(writer, "textureImageData", TextureImageData);
                        }
                    }

                    writer.WriteEndElement();
                }

                fileStream.Close();
            }
        }
Exemplo n.º 21
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);
        }
Exemplo n.º 22
0
 public static byte[] Compress(byte[] bytData)
 {
     MemoryStream ms = new MemoryStream();
     Stream s = new DeflaterOutputStream(ms);
     s.Write(bytData, 0, bytData.Length);
     s.Close();
     byte[] compressedData = (byte[])ms.ToArray();
     return compressedData;
 }
Exemplo n.º 23
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;
        }
Exemplo n.º 24
0
            /// <summary>
            /// Saves the updates into a hidden field.
            /// </summary>
            /// <param name="writer">Ignored.</param>
            protected override void Render(HtmlTextWriter writer)
            {
                // serialize object into compressed stream
                MemoryStream deflatedStream = new MemoryStream();
                DeflaterOutputStream deflater = new DeflaterOutputStream(deflatedStream,
                                                                         new Deflater(Deflater.BEST_COMPRESSION, true));
                if (m_Updates != null)
                    serializer.Serialize(deflater, m_Updates);
                
                deflater.Close();

                // get compressed characters
                byte[] deflatedBytes = deflatedStream.ToArray();
                char[] deflatedChars = new char[(int)(Math.Ceiling((double)deflatedBytes.Length / 3) * 4)];
                Convert.ToBase64CharArray(deflatedBytes, 0, deflatedBytes.Length, deflatedChars, 0);

                // register the compressed string as a hidden field
                ScriptManager.RegisterHiddenField(Page, UpdatesFieldName, new string(deflatedChars));
            }
		public void DeflatorStreamOwnership()
		{
			TrackedMemoryStream memStream = new TrackedMemoryStream();
			DeflaterOutputStream 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");
			
		}
Exemplo n.º 26
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);
            }
        }
Exemplo n.º 27
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());
 }
Exemplo n.º 28
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();
        }
Exemplo n.º 29
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;
        }
Exemplo n.º 30
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;
		}
Exemplo n.º 31
0
        private void writeCMV(string outFilename)
        {
            byte[] target, compressed;
            ExtensionType extension;
            DeflaterOutputStream zipOutStream;
            MemoryStream stream;
            MemoryStream memoryStream;

            cols = Columns;
            rows = Rows;

            if (frames.Count == 0)
            {
                throw new CMVException("There are no frames to save.");
            }

            if (cols == 0 || rows == 0)
            {
                throw new CMVException(String.Format("Invalid columns ({0}), rows ({1}) combination", cols, rows));
            }

            extension = checkExtension(outFilename);

            stream = new MemoryStream();

            byte[] intBytes = new byte[4];

            intBytes = BitConverter.GetBytes((Int32)version);
            stream.Write(intBytes, 0, 4);

            intBytes = BitConverter.GetBytes((Int32)cols);
            stream.Write(intBytes, 0, 4);

            intBytes = BitConverter.GetBytes((Int32)rows);
            stream.Write(intBytes, 0, 4);

            intBytes = BitConverter.GetBytes((Int32)delayRate);
            stream.Write(intBytes, 0, 4);

            // Sounds
            if (version == 10001)
            {
                intBytes = BitConverter.GetBytes((Int32)numSounds);
                stream.Write(intBytes, 0, 4);

                stream.Write(soundNames, 0, soundNames.Length);

                stream.Write(soundTimings, 0, soundTimings.Length);
            }

            //int frameSize = (int)(cols * rows);
            //frameSize += frameSize;

            byte[] chunk;
            int i = 0;
            int framesInChunk;
            int compressedChunkSize;
            byte[] frame;
            while(i < frames.Count)
            {
                if ((frames.Count - i) > FRAMES_PER_CHUNK)
                {
                    framesInChunk = FRAMES_PER_CHUNK;
                }
                else
                {
                    framesInChunk = (Int32)(frames.Count - i);
                }

                memoryStream = new MemoryStream();
                zipOutStream = new DeflaterOutputStream(memoryStream, new Deflater(Deflater.BEST_COMPRESSION));

                for (int j = 0; j < framesInChunk; j++)
                {
                    frame = frames[i + j].Frame;
                    zipOutStream.Write(frame, 0, frame.Length);
                }

                zipOutStream.Finish();

                compressedChunkSize = (Int32)memoryStream.Length;

                intBytes = BitConverter.GetBytes((Int32)compressedChunkSize);
                stream.Write(intBytes, 0, 4);

                chunk = memoryStream.ToArray();
                stream.Write(chunk, 0, chunk.Length);

                i = i + framesInChunk;

                zipOutStream.Close();
            }

            target = stream.ToArray();
            stream.Close();

            if (extension == ExtensionType.CCMV)
            {
                compressed = new byte[0];

                memoryStream = new MemoryStream(target);
                zipOutStream = new DeflaterOutputStream(memoryStream);
                zipOutStream.Write(target, 0, target.Length);

                compressed = new byte[memoryStream.Length];
                memoryStream.Position = 0;
                memoryStream.Read(compressed, 0, (Int32)memoryStream.Length);
                File.WriteAllBytes(outFilename, compressed);
            }
            else
            {
                File.WriteAllBytes(outFilename, target);
            }

            stream.Close();
            stream.Dispose();
        }