} // End Sub CompressFile public static void DeflateCompressFile(string FileToCompress, string CompressedFile) { //byte[] buffer = new byte[1024 * 1024 * 64]; byte[] buffer = new byte[1024 * 1024]; // 1MB using (System.IO.FileStream sourceFile = System.IO.File.OpenRead(FileToCompress)) { using (System.IO.FileStream destinationFile = System.IO.File.Create(CompressedFile)) { using (System.IO.Compression.DeflateStream output = new System.IO.Compression.DeflateStream(destinationFile, System.IO.Compression.CompressionMode.Compress)) { int bytesRead = 0; while (bytesRead < sourceFile.Length) { int ReadLength = sourceFile.Read(buffer, 0, buffer.Length); output.Write(buffer, 0, ReadLength); output.Flush(); bytesRead += ReadLength; } // Whend destinationFile.Flush(); } // End Using System.IO.Compression.GZipStream output destinationFile.Close(); } // End Using System.IO.FileStream destinationFile // Close the files. sourceFile.Close(); } // End Using System.IO.FileStream sourceFile } // End Sub CompressFile
internal ParticleSystemCompiledShaderData(byte[] shaderCode, bool isXbox, int colourIndex, int userIndex, int lifeIndex) { if (shaderCode == null) throw new ArgumentNullException(); //compress the shader code if (isXbox) { //deflate stream isn't supported shaderCode = Xen.Graphics.ShaderSystem.ShaderSystemBase.SimpleCompress(shaderCode); } else { #if !XBOX360 using (MemoryStream stream = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write(shaderCode.Length); using (System.IO.Compression.DeflateStream d = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Compress)) { d.Write(shaderCode, 0, shaderCode.Length); d.Flush(); } shaderCode = stream.ToArray(); } #endif } this.CompressedShaderCode = shaderCode; this.ColourSamplerIndex = colourIndex; this.UserSamplerIndex = userIndex; this.LifeSamplerIndex = lifeIndex; }
public static unsafe byte[] Compress(byte[] buffer) { // TODO : rename to unity flag #if SCRIPT_ENABLED using (var compressStream = new System.IO.MemoryStream()) using (var compressor = new System.IO.Compression.DeflateStream(compressStream, System.IO.Compression.CompressionLevel.Optimal)) { UInt32 adder = 0; fixed(byte *b = buffer) { adder = CalcAdler32(b, (UInt32)buffer.Length); } compressor.Write(buffer, 0, buffer.Count()); compressor.Close(); var compressed = compressStream.ToArray(); List <byte[]> dst = new List <byte[]>(); dst.Add(new byte[] { 0x78, 0x9c }); dst.Add(compressed); dst.Add(BitConverter.GetBytes(adder).Reverse().ToArray()); return(dst.SelectMany(_ => _).ToArray()); } #else return(null); #endif }
public void WillDecodeDeflateResponse() { var testable = new TestableJavaScriptReducer(); var mockWebResponse = new Mock <WebResponse>(); var ms = new MemoryStream(); var stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress); stream.Write(new UTF8Encoding().GetBytes("my response"), 0, "my response".Length); stream.Close(); var encodedArray = ms.ToArray(); ms.Close(); stream.Dispose(); ms.Dispose(); mockWebResponse.Setup(x => x.GetResponseStream()).Returns(new MemoryStream(encodedArray)); mockWebResponse.Setup(x => x.Headers).Returns(new WebHeaderCollection() { { "Content-Encoding", "deflate" } }); testable.Mock <IWebClientWrapper>().Setup(x => x.Download <JavaScriptResource>("http://host/js1.js")).Returns(mockWebResponse.Object); testable.Mock <IMinifier>().Setup(x => x.Minify <JavaScriptResource>("my response;\r\n")).Returns("min"); var result = testable.ClassUnderTest.Process("http://host/js1.js::"); testable.Mock <IStore>().Verify( x => x.Save(Encoding.UTF8.GetBytes("min").MatchEnumerable(), result, "http://host/js1.js::"), Times.Once()); ms.Dispose(); }
private static byte[] StreamCompress(byte[] data) { using var val = new MemoryStream(); using (var compressor = new System.IO.Compression.DeflateStream(val, System.IO.Compression.CompressionLevel.Optimal)) { compressor.Write(data, 0, data.Length); } return(val.ToArray()); }
/// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream. </param><param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream. </param><param name="count">The number of bytes to be written to the current stream. </param> public override void Write(byte[] buffer, int offset, int count) { #if !PORTABLE _deflateStream.Write(buffer, offset, count); _adler = Adler32.Update(_adler, buffer, offset, count); #endif }
/// <summary> /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream. </param><param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream. </param><param name="count">The number of bytes to be written to the current stream. </param> public override void Write(byte[] buffer, int offset, int count) { #if PORTABLE ExceptionHelper.ThrowNotSupported(); #else _deflateStream.Write(buffer, offset, count); _adler = Adler32.Update(_adler, buffer, offset, count); #endif }
/// <summary> /// Compresses a byte array. /// </summary> /// <param name="bytes">Byte array to be compressed.</param> /// <returns>A compressed byte array.</returns> static public byte[] Compress(byte[] bytes) { MemoryStream outStream = new MemoryStream(); using (System.IO.Compression.DeflateStream deflate = new System.IO.Compression.DeflateStream(outStream, System.IO.Compression.CompressionMode.Compress)) { deflate.Write(bytes, 0, bytes.Length); } return(outStream.ToArray()); }
public byte[] EncodeDeflate(byte[] plainData) { using (MemoryStream ms = new MemoryStream()) { using (System.IO.Compression.DeflateStream deflate = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { deflate.Write(plainData, 0, plainData.Length); } return(ms.ToArray()); } }
static public byte[] Deflate(byte[] input) { using (var deflatedStream = new System.IO.MemoryStream()) using (var compressor = new System.IO.Compression.DeflateStream( deflatedStream, System.IO.Compression.CompressionMode.Compress)) { compressor.Write(input, 0, input.Length); compressor.Close(); return(deflatedStream.ToArray()); } }
/// <summary> /// Compresses the byte array using System.IO.Compression.DeflateStream /// </summary> /// <param name="bytes">The byte array to compress</param> /// <returns>A byte array of compressed data</returns> //[System.Diagnostics.DebuggerStepThrough] public static byte[] AsCompressed(this byte[] bytes) { //var output = new MemoryStream(); using (var output = new MemoryStream()) { using (var deflater = new System.IO.Compression.DeflateStream(output, System.IO.Compression.CompressionMode.Compress)) { deflater.Write(bytes, 0, bytes.Length); } return(output.ToArray()); } }
public static byte[] Compress(byte[] bytes) { var srcStream = new System.IO.MemoryStream(bytes); var dstStream = new System.IO.MemoryStream(); srcStream.Position = 0; var stream = new System.IO.Compression.DeflateStream(dstStream, System.IO.Compression.CompressionMode.Compress); byte[] buffer = new byte[4096]; int numRead; while ((numRead = srcStream.Read(buffer, 0, buffer.Length)) != 0) stream.Write(buffer, 0, numRead); stream.Close(); return dstStream.ToArray(); }
public static void WriteDynamics(GameClient client) { if (dynamics == null) { if (BaseVobInstance.GetCountDynamics() > 0 && ModelInstance.CountDynamics > 0) { PacketWriter strm = new PacketWriter(); // MODELS if (strm.Write(ModelInstance.CountDynamics > 0)) { strm.Write((ushort)ModelInstance.CountDynamics); ModelInstance.ForEachDynamic(model => { model.WriteStream(strm); }); } // INSTANCES if (strm.Write(BaseVobInstance.GetCountDynamics() > 0)) { strm.Write((ushort)BaseVobInstance.GetCountDynamics()); BaseVobInstance.ForEachDynamic(v => { strm.Write((byte)v.ScriptObject.GetVobType()); v.WriteStream(strm); }); } byte[] arr = strm.CopyData(); int decomp = arr.Length; using (var ms = new System.IO.MemoryStream(decomp)) { using (var ds = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress)) { ds.Write(arr, 0, decomp); } arr = ms.ToArray(); } strm.Reset(); strm.Write((byte)ServerMessages.DynamicsMessage); strm.Write(decomp); strm.Write(arr, 0, arr.Length); dynamics = strm.CopyData(); } else { return; } } client.Send(dynamics, dynamics.Length, NetPriority.Low, NetReliability.Reliable, '\0'); }
private byte[] AddFileToPak(byte[] oldRange, List <byte> fileCore, string FileName) { List <byte> list = new List <byte>(); int num = fileCore.Count; int num2 = (int)Math.Ceiling(oldRange.Length / 65536m); int[] array = new int[num2]; Console.WriteLine("Sectors: " + num2.ToString()); for (int i = 0; i < num2; i++) { Console.WriteLine(FileName + " : " + i.ToString()); byte[] array2 = new byte[(oldRange.Length - 65536 * i > 65536) ? 65536 : (oldRange.Length - 65536 * i)]; Buffer.BlockCopy(oldRange, 65536 * i, array2, 0, array2.Length); using (MemoryStream memoryStream = new MemoryStream()) { using (System.IO.Compression.DeflateStream deflateStream = new System.IO.Compression.DeflateStream(memoryStream, System.IO.Compression.CompressionMode.Compress)) { deflateStream.Write(array2, 0, array2.Length); } list.AddRange(BitConverter.GetBytes((short)-25480)); byte[] array3 = memoryStream.ToArray(); list.AddRange(array3); list.AddRange(BitConverter.GetBytes(Utilities.Adler32Checksum(array2)).Reverse()); array[i] = array3.Length + 6; } } byte[] array4 = new byte[57 + 16 * num2]; Buffer.BlockCopy(BitConverter.GetBytes(num), 0, array4, 0, 4); Buffer.BlockCopy(BitConverter.GetBytes(list.Count), 0, array4, 8, 4); Buffer.BlockCopy(BitConverter.GetBytes(oldRange.Length), 0, array4, 16, 4); Buffer.BlockCopy(BitConverter.GetBytes(1), 0, array4, 24, 4); Buffer.BlockCopy(SHA1.Create().ComputeHash(list.ToArray()), 0, array4, 28, 20); Buffer.BlockCopy(BitConverter.GetBytes(num2), 0, array4, 48, 4); num += array4.Length; for (int j = 0; j < num2; j++) { Buffer.BlockCopy(BitConverter.GetBytes((long)num), 0, array4, 52 + j * 16, 4); num += array[j]; Buffer.BlockCopy(BitConverter.GetBytes((long)num), 0, array4, 60 + j * 16, 4); } Buffer.BlockCopy(new byte[] { 1 }, 0, array4, 55 + num2 * 16, 1); byte[] array5 = new byte[FileName.Length + 5 + array4.Length]; Array.Copy(Utilities.FileNameToHeaderBytes(FileName), 0, array5, 0, FileName.Length + 5); Array.Copy(array4, 0, array5, FileName.Length + 5, array4.Length); fileCore.AddRange(array4); fileCore.AddRange(list); return(array5); }
private byte[] Compress(byte[] inputBuffer) { byte[] output; using (var outputstream = new MemoryStream()) { using (var algostream = new System.IO.Compression.DeflateStream(outputstream, System.IO.Compression.CompressionLevel.Fastest, true)) { algostream.Write(inputBuffer, 0, inputBuffer.Length); } outputstream.Seek(0L, SeekOrigin.Begin); output = outputstream.ToArray(); } return(output); }
/// <summary> /// Compresses the byte array using System.IO.Compression.DeflateStream /// </summary> /// <param name="bytes">The byte array to compress</param> /// <returns>A byte array of compressed data</returns> public static byte[] AsCompressed(this byte[] bytes) { var output = new MemoryStream(); using (var deflater = new System.IO.Compression.DeflateStream(output, System.IO.Compression.CompressionMode.Compress)) { deflater.Write(bytes, 0, bytes.Length); } #if WINDOWS_PORTABLE || WINDOWS_UWP || NETCOREAPP1_0 || NETCOREAPP1_1 return(output.ToArray()); #else return(output.GetBuffer()); #endif }
private static byte[] DeflateCompressor(byte[] bytes) //Для старых (версии 8 и 9) и новых архивов { byte[] retVal; using (MemoryStream compressedMemoryStream = new MemoryStream()) { System.IO.Compression.DeflateStream compressStream = new System.IO.Compression.DeflateStream(compressedMemoryStream, System.IO.Compression.CompressionMode.Compress, true); compressStream.Write(bytes, 0, bytes.Length); compressStream.Close(); retVal = new byte[compressedMemoryStream.Length]; compressedMemoryStream.Position = 0L; compressedMemoryStream.Read(retVal, 0, retVal.Length); compressedMemoryStream.Close(); compressStream.Close(); } return(retVal); }
public static string Base64CompressUrlEncode(string xml) { //http://stackoverflow.com/questions/12090403/how-do-i-correctly-prepare-an-http-redirect-binding-saml-request-using-c-sharp string base64 = string.Empty; var bytes = Encoding.UTF8.GetBytes(xml); using (var output = new MemoryStream()) { using (var zip = new System.IO.Compression.DeflateStream(output, System.IO.Compression.CompressionMode.Compress)) { zip.Write(bytes, 0, bytes.Length); } base64 = Convert.ToBase64String(output.ToArray()); } return(HttpUtility.UrlEncode(base64)); }
public override void Write(byte[] array, int offset, int count) { if (count == 0) { return; } if (!initdone) { doInit(); } if (deflateStream == null) { initStream(); } deflateStream.Write(array, offset, count); adler32.Update(array, offset, count); }
public byte[] GetRawData(bool compress) { var bytes = new List <byte>(); //Add header bytes.Add((byte)ModuleMatrix.Count); //Build data queue var dataQueue = new Queue <int>(); foreach (var row in ModuleMatrix) { foreach (var module in row) { dataQueue.Enqueue((bool)module ? 1 : 0); } } for (int i = 0; i < 8 - (ModuleMatrix.Count * ModuleMatrix.Count) % 8; i++) { dataQueue.Enqueue(0); } //Process queue while (dataQueue.Count > 0) { byte b = 0; for (int i = 7; i >= 0; i--) { b += (byte)(dataQueue.Dequeue() << i); } bytes.Add(b); } var rawData = bytes.ToArray(); //Compress stream (optional) if (compress) { var output = new System.IO.MemoryStream(); using (var dstream = new System.IO.Compression.DeflateStream(output, System.IO.Compression.CompressionMode.Compress)) { dstream.Write(rawData, 0, rawData.Length); } rawData = output.ToArray(); } return(rawData); }
public static string Compress(string strSource) { if (strSource == null) throw new System.ArgumentException("字符串为空!"); System.Text.Encoding encoding = System.Text.Encoding.Unicode; byte[] buffer = encoding.GetBytes(strSource); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true); stream.Write(buffer, 0, buffer.Length); stream.Close(); buffer = ms.ToArray(); ms.Close(); //return buffer; return Convert.ToBase64String(buffer); //将压缩后的byte[]转换为Base64String }
} // End Function Compress // http://www.dotnetperls.com/compress /// <summary> /// Compresses byte array to new byte array. /// </summary> public static byte[] DeflateCompress(byte[] raw) { byte[] baRetVal; using (System.IO.MemoryStream memstrm = new System.IO.MemoryStream()) { using (System.IO.Compression.DeflateStream gzip = new System.IO.Compression.DeflateStream(memstrm, System.IO.Compression.CompressionMode.Compress, true)) { gzip.Write(raw, 0, raw.Length); gzip.Flush(); } // End Using System.IO.Compression.GZipStream gzip memstrm.Flush(); baRetVal = memstrm.ToArray(); memstrm.Close(); } // End Using System.IO.MemoryStream memory return(baRetVal); } // End Function Compress
private void OnSerializing(StreamingContext context) { if (_data.Length > 256) { if (_compressed == false) { using (var compressedData = new MemoryStream()) { using (var cs = new System.IO.Compression.DeflateStream(compressedData, System.IO.Compression.CompressionLevel.Optimal)) { cs.Write(_data, 0, _data.Length); } compressedData.Flush(); _data = compressedData.ToArray(); _compressed = true; } } } }
/// <summary> /// Compress using deflate algorithm. /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] Compress(byte[] data) { byte[] array = null; try { using (MemoryStream memoryStream = new MemoryStream()) using (System.IO.Compression.DeflateStream compressionStream = new System.IO.Compression.DeflateStream(memoryStream , System.IO.Compression.CompressionMode.Compress)) { compressionStream.Write(data, 0, data.Length); compressionStream.Close(); return(memoryStream.ToArray()); } } catch (Exception exception) { Energy.Core.Bug.Catch(exception); } return(array); }
public static byte[] Compress(string strSource) { if (strSource == null) { throw new System.ArgumentException("字符串为空!"); } System.Text.Encoding encoding = System.Text.Encoding.Unicode; byte[] buffer = encoding.GetBytes(strSource); System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true); stream.Write(buffer, 0, buffer.Length); stream.Close(); buffer = ms.ToArray(); ms.Close(); return(buffer); // return Convert.ToBase64String(buffer); //将压缩后的byte[]转换为Base64String }
//字符串压缩 public static string Compress(string strSource) { if (strSource == null || strSource.Length > 1024 * 1024) { throw new System.ArgumentException("字符串为空或长度太大!"); } System.Text.Encoding encoding = System.Text.Encoding.Unicode; byte[] buffer = encoding.GetBytes(strSource); //byte[] buffer = Convert.FromBase64String(strSource); //传入的字符串不一定是Base64String类型,这样写不行 System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.IO.Compression.DeflateStream stream = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true); stream.Write(buffer, 0, buffer.Length); stream.Close(); buffer = ms.ToArray(); ms.Close(); return(Convert.ToBase64String(buffer)); //将压缩后的byte[]转换为Base64String }
private XmlNode comprimirDatos(XmlElement propiedades, CompressionAlgorithm compresor) { string valor = propiedades.OuterXml; System.IO.MemoryStream stream = new MemoryStream(valor.Length); System.IO.Stream streamCompresor = null; switch (compresor) { case CompressionAlgorithm.Deflate: streamCompresor = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Compress); break; case CompressionAlgorithm.Gzip: streamCompresor = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Compress); break; #if LZMAPRESENT case CompressionAlgorithm.LZMA: streamCompresor = new System.IO.Compression.LzmaStream(stream, System.IO.Compression.CompressionMode.Compress); break; #endif default: streamCompresor = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Compress); break; } byte[] datos = System.Text.Encoding.Default.GetBytes(valor); streamCompresor.Write(datos, 0, datos.Length); streamCompresor.Close(); byte[] datosComprimidos = stream.ToArray(); stream.Close(); // XmlElement propiedades = documento.CreateElement("properties"); propiedades.InnerText = Convert.ToBase64String(datosComprimidos); return(propiedades); }
internal void WriteToStream(Stream writer) { System.Diagnostics.Debug.Assert(!IsReadOnly); System.Diagnostics.Debug.Assert(positionOfCompressedDataInArchive == 0); if (uncompressedData != null) { if (uncompressedData.CanWrite) { throw new Exception("Unclosed writable handle to " + Name + " still exists at Save time"); } MemoryStream compressedDataStream = new RepairedMemoryStream((int)(uncompressedData.Length * 5 / 8)); Stream compressor = new System.IO.Compression.DeflateStream(compressedDataStream, System.IO.Compression.CompressionMode.Compress); compressor.Write(uncompressedData.GetBuffer(), 0, (int)uncompressedData.Length); compressor.Close(); compressionMethod = CompressionMethod.Deflate; compressedLength = (int)compressedDataStream.Length; compressedData = compressedDataStream.GetBuffer(); } System.Diagnostics.Debug.Assert(compressedData != null); WriteZipFileHeader(writer); writer.Write(compressedData, 0, compressedLength); }
public static void SendHttpResponse(HttpContext context, string contentToSend) { CompressionSupport compressionSupport = context.GetCompressionSupport(); string acceptEncoding = context.Request.Headers["Accept-Encoding"]; if (compressionSupport != CompressionSupport.None) { if (context.Response.Headers.AllKeys.FirstOrDefault(key => key.Equals(HttpExtensions.ResponseCompressionHeaderKey)) == null) { context.AddCompressionHeaders(compressionSupport); } System.IO.MemoryStream stream = null; using (stream = new System.IO.MemoryStream()) { byte[] content = System.Text.Encoding.UTF8.GetBytes(contentToSend); if (compressionSupport == CompressionSupport.Deflate) { using (System.IO.Compression.DeflateStream zip = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Compress, false)) { zip.Write(content, 0, content.Length); } } else if (compressionSupport == CompressionSupport.GZip) { using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Compress, false)) { zip.Write(content, 0, content.Length); } } } context.Response.BinaryWrite(stream.ToByteArray()); } else { context.Response.Write(contentToSend); } context.Response.Flush(); }
/// <summary> /// Compresses and returns the <paramref name="source"/> byte array using the <see cref="System.IO.Compression.DeflateStream"/> algorithm. /// </summary> /// <param name="source">The byte array to compress.</param> /// <returns>The compressed <paramref name="source"/> byte array.</returns> public byte[] Compress(byte[] source) { if (source == null) { return(source); } byte[] result = null; using (var ms = new System.IO.MemoryStream()) { using (var ds = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { ds.Write(source, 0, source.Length); ds.Flush(); ds.Close(); } result = ms.ToArray(); ms.Close(); } return(result); }
/// <summary> /// Compress given data using compressor named in contentEncoding. Set the response header accordingly. /// </summary> /// <param name="data">PhpBytes or string to be compressed.</param> /// <param name="httpcontext">Current HttpContext.</param> /// <param name="contentEncoding">gzip or deflate</param> /// <returns>Byte stream of compressed data.</returns> private static PhpBytes DoGzipHandler(object data, HttpContext /*!*/ httpcontext, ContentEncoding contentEncoding) { PhpBytes phpbytes = data as PhpBytes; var inputbytes = (phpbytes != null) ? phpbytes.ReadonlyData : Configuration.Application.Globalization.PageEncoding.GetBytes(PHP.Core.Convert.ObjectToString(data)); using (var outputStream = new System.IO.MemoryStream()) { System.IO.Stream compressionStream; switch (contentEncoding) { case ContentEncoding.gzip: compressionStream = new System.IO.Compression.GZipStream(outputStream, System.IO.Compression.CompressionMode.Compress); break; case ContentEncoding.deflate: compressionStream = new System.IO.Compression.DeflateStream(outputStream, System.IO.Compression.CompressionMode.Compress); break; default: throw new ArgumentException("Not recognized content encoding to be compressed to.", "contentEncoding"); } using (compressionStream) { compressionStream.Write(inputbytes, 0, inputbytes.Length); } //Debug.Assert( // ScriptContext.CurrentContext.Headers["content-encoding"] != contentEncoding, // "The content encoding was already set to '" + contentEncoding + "'. The ob_gzhandler() was called subsequently probably."); ScriptContext.CurrentContext.Headers["content-encoding"] = contentEncoding.ToString(); return(new PhpBytes(outputStream.ToArray())); } }
/// <summary> /// Writes blob and it's header to the underlaying stream. /// </summary> /// <param name="blobType">The type of the blob.</param> /// <param name="blobContent">The pbf serialized content of the blob.</param> private void WriteBlob(string blobType, byte[] blobContent) { Blob blob = new Blob(); if (this.Settings.Compression == CompressionMode.None) { blob.Raw = blobContent; } else if (this.Settings.Compression == CompressionMode.ZlibDeflate) { MemoryStream zlibStream = new MemoryStream(); //ZLIB header zlibStream.WriteByte(120); zlibStream.WriteByte(156); using (System.IO.Compression.DeflateStream deflateSteram = new System.IO.Compression.DeflateStream(zlibStream, System.IO.Compression.CompressionMode.Compress, true)) { deflateSteram.Write(blobContent, 0, blobContent.Length); } blob.RawSize = (int)blobContent.Length; blob.ZlibData = new byte[zlibStream.Length]; Array.Copy(zlibStream.GetBuffer(), blob.ZlibData, zlibStream.Length); } MemoryStream blobStream = new MemoryStream(); Serializer.Serialize <Blob>(blobStream, blob); BlobHeader header = new BlobHeader(); header.Type = blobType; header.DataSize = (int)blobStream.Length; Serializer.SerializeWithLengthPrefix(_output, header, PrefixStyle.Fixed32BigEndian); blobStream.WriteTo(_output); }
// Convert an object to a byte array public static byte[] ToBytes(object obj) { if(obj == null) return new byte[1] { 0 }; if (obj is string) { if (((string)obj) == "") return new byte[1] { 4 }; var buf = System.Text.Encoding.UTF8.GetBytes((string)obj); using (var ms = new MemoryStream()) { using (var zs = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { zs.Write(buf, 0, buf.Length); } if (ms.Length < buf.Length) return ms.ToArray().Prepend((byte)2).ToArray(); else return buf.Prepend((byte)3).ToArray(); } } else { using (var ms = new MemoryStream()) { ms.Write(new byte[1] { 1 }, 0, 1); using (var zs = new System.IO.Compression.DeflateStream(ms, System.IO.Compression.CompressionMode.Compress, true)) { var f = new BinaryFormatter(); f.Serialize(zs, obj); } return ms.ToArray(); } } }
/// <summary> /// Compress given data using compressor named in contentEncoding. Set the response header accordingly. /// </summary> /// <param name="data">PhpBytes or string to be compressed.</param> /// <param name="httpcontext">Current HttpContext.</param> /// <param name="contentEncoding">gzip or deflate</param> /// <returns>Byte stream of compressed data.</returns> private static PhpBytes DoGzipHandler(object data, HttpContext/*!*/httpcontext, ContentEncoding contentEncoding) { PhpBytes phpbytes = data as PhpBytes; var inputbytes = (phpbytes != null) ? phpbytes.ReadonlyData : Configuration.Application.Globalization.PageEncoding.GetBytes(PHP.Core.Convert.ObjectToString(data)); using (var outputStream = new System.IO.MemoryStream()) { System.IO.Stream compressionStream; switch (contentEncoding) { case ContentEncoding.gzip: compressionStream = new System.IO.Compression.GZipStream(outputStream, System.IO.Compression.CompressionMode.Compress); break; case ContentEncoding.deflate: compressionStream = new System.IO.Compression.DeflateStream(outputStream, System.IO.Compression.CompressionMode.Compress); break; default: throw new ArgumentException("Not recognized content encoding to be compressed to.", "contentEncoding"); } using (compressionStream) { compressionStream.Write(inputbytes, 0, inputbytes.Length); } //Debug.Assert( // ScriptContext.CurrentContext.Headers["content-encoding"] != contentEncoding, // "The content encoding was already set to '" + contentEncoding + "'. The ob_gzhandler() was called subsequently probably."); ScriptContext.CurrentContext.Headers["content-encoding"] = contentEncoding.ToString(); return new PhpBytes(outputStream.ToArray()); } }
private void WriteDataChunks() { byte[] pixels = _image.Pixels; byte[] data = new byte[_image.PixelWidth * _image.PixelHeight * 4 + _image.PixelHeight]; int rowLength = _image.PixelWidth * 4 + 1; for (int y = 0; y < _image.PixelHeight; y++) { byte compression = 0; if (y > 0) { compression = 2; } data[y * rowLength] = compression; for (int x = 0; x < _image.PixelWidth; x++) { // Calculate the offset for the new array. int dataOffset = y * rowLength + x * 4 + 1; // Calculate the offset for the original pixel array. int pixelOffset = (y * _image.PixelWidth + x) * 4; data[dataOffset + 0] = pixels[pixelOffset + 0]; data[dataOffset + 1] = pixels[pixelOffset + 1]; data[dataOffset + 2] = pixels[pixelOffset + 2]; data[dataOffset + 3] = pixels[pixelOffset + 3]; if (y > 0) { int lastOffset = ((y - 1) * _image.PixelWidth + x) * 4; data[dataOffset + 0] -= pixels[lastOffset + 0]; data[dataOffset + 1] -= pixels[lastOffset + 1]; data[dataOffset + 2] -= pixels[lastOffset + 2]; data[dataOffset + 3] -= pixels[lastOffset + 3]; } } } byte[] buffer = null; int bufferLength = 0; MemoryStream memoryStream = null; try { memoryStream = new MemoryStream(); //using (Ionic.Zlib.DeflateStream zStream = new Ionic.Zlib.DeflateStream(memoryStream, Ionic.Zlib.CompressionMode.Compress)) using (System.IO.Compression.DeflateStream zStream = new System.IO.Compression.DeflateStream(memoryStream, System.IO.Compression.CompressionMode.Compress)) { zStream.Write(data, 0, data.Length); zStream.Flush(); bufferLength = (int)memoryStream.Length; buffer = memoryStream.GetBuffer(); zStream.Close(); } //using (DeflaterOutputStream zStream = new DeflaterOutputStream(memoryStream)) //{ // zStream.Write(data, 0, data.Length); // zStream.Flush(); // zStream.Finish(); // bufferLength = (int)memoryStream.Length; // buffer = memoryStream.GetBuffer(); //} } finally { if (memoryStream != null) { memoryStream.Dispose(); } } int numChunks = bufferLength / MaxBlockSize; if (bufferLength % MaxBlockSize != 0) { numChunks++; } for (int i = 0; i < numChunks; i++) { int length = bufferLength - i * MaxBlockSize; if (length > MaxBlockSize) { length = MaxBlockSize; } WriteChunk(PngChunkTypes.Data, buffer, i * MaxBlockSize, length); } }
public static void SendHttpResponse(HttpContext context, string contentToSend) { CompressionSupport compressionSupport = context.GetCompressionSupport(); string acceptEncoding = context.Request.Headers["Accept-Encoding"]; if (compressionSupport != CompressionSupport.None) { if (context.Response.Headers.AllKeys.FirstOrDefault(key=>key.Equals(HttpExtensions.ResponseCompressionHeaderKey)) == null) context.AddCompressionHeaders(compressionSupport); System.IO.MemoryStream stream = null; using (stream = new System.IO.MemoryStream()) { byte[] content = System.Text.Encoding.UTF8.GetBytes(contentToSend); if (compressionSupport == CompressionSupport.Deflate) { using (System.IO.Compression.DeflateStream zip = new System.IO.Compression.DeflateStream(stream, System.IO.Compression.CompressionMode.Compress, false)) { zip.Write(content, 0, content.Length); } } else if (compressionSupport == CompressionSupport.GZip) { using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Compress, false)) { zip.Write(content, 0, content.Length); } } } context.Response.BinaryWrite(stream.ToByteArray()); } else { context.Response.Write(contentToSend); } context.Response.Flush(); }
public static byte[] Zip(byte[] data) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.Compression.DeflateStream zStream = new System.IO.Compression.DeflateStream( stream, System.IO.Compression.CompressionMode.Compress, true); zStream.Write(data, 0, data.Length); zStream.Close(); return stream.ToArray(); }
/// <summary> /// Writes blob and it's header to the underlaying stream. /// </summary> /// <param name="blobType">The type of the blob.</param> /// <param name="blobContent">The pbf serialized content of the blob.</param> private void WriteBlob(string blobType, byte[] blobContent) { Blob blob = new Blob(); if (this.Settings.Compression == CompressionMode.None) { blob.Raw = blobContent; } else if (this.Settings.Compression == CompressionMode.ZlibDeflate) { MemoryStream zlibStream = new MemoryStream(); //ZLIB header zlibStream.WriteByte(120); zlibStream.WriteByte(156); using (System.IO.Compression.DeflateStream deflateSteram = new System.IO.Compression.DeflateStream(zlibStream, System.IO.Compression.CompressionMode.Compress, true)) { deflateSteram.Write(blobContent, 0, blobContent.Length); } blob.RawSize = (int)blobContent.Length; blob.ZlibData = new byte[zlibStream.Length]; Array.Copy(zlibStream.GetBuffer(), blob.ZlibData, zlibStream.Length); } MemoryStream blobStream = new MemoryStream(); Serializer.Serialize<Blob>(blobStream, blob); BlobHeader header = new BlobHeader(); header.Type = blobType; header.DataSize = (int)blobStream.Length; Serializer.SerializeWithLengthPrefix(_output, header, PrefixStyle.Fixed32BigEndian); blobStream.WriteTo(_output); }
public void Zlib_Streams_VariousSizes() { byte[] working = new byte[WORKING_BUFFER_SIZE]; int n = -1; Int32[] Sizes = { 8000, 88000, 188000, 388000, 580000, 1580000 }; for (int p = 0; p < Sizes.Length; p++) { // both binary and text files for (int m = 0; m < 2; m++) { int sz = this.rnd.Next(Sizes[p]) + Sizes[p]; string FileToCompress = System.IO.Path.Combine(TopLevelDir, String.Format("Zlib_Streams.{0}.{1}", sz, (m == 0) ? "txt" : "bin")); Assert.IsFalse(System.IO.File.Exists(FileToCompress), "The temporary file '{0}' already exists.", FileToCompress); TestContext.WriteLine("Creating file {0} {1} bytes", FileToCompress, sz); if (m == 0) CreateAndFillFileText(FileToCompress, sz); else _CreateAndFillBinary(FileToCompress, sz, false); int crc1 = DoCrc(FileToCompress); TestContext.WriteLine("Initial CRC: 0x{0:X8}", crc1); // try both GZipStream and DeflateStream for (int k = 0; k < 2; k++) { // compress with Alienlab.and System.IO.Compression for (int i = 0; i < 2; i++) { string CompressedFileRoot = String.Format("{0}.{1}.{2}.compressed", FileToCompress, (k == 0) ? "GZIP" : "DEFLATE", (i == 0) ? "Ionic" : "BCL"); int x = k + i * 2; int z = (x == 0) ? 4 : 1; // why 4 trials?? (only for GZIP and Alienlab. for (int h = 0; h < z; h++) { string CompressedFile = (x == 0) ? CompressedFileRoot + ".trial" + h : CompressedFileRoot; using (var input = System.IO.File.OpenRead(FileToCompress)) { using (var raw = System.IO.File.Create(CompressedFile)) { Stream compressor = null; try { switch (x) { case 0: // k == 0, i == 0 compressor = new Alienlab.Zlib.GZipStream(raw, CompressionMode.Compress, true); break; case 1: // k == 1, i == 0 compressor = new Alienlab.Zlib.DeflateStream(raw, CompressionMode.Compress, true); break; case 2: // k == 0, i == 1 compressor = new System.IO.Compression.GZipStream(raw, System.IO.Compression.CompressionMode.Compress, true); break; case 3: // k == 1, i == 1 compressor = new System.IO.Compression.DeflateStream(raw, System.IO.Compression.CompressionMode.Compress, true); break; } //TestContext.WriteLine("Compress with: {0} ..", compressor.GetType().FullName); TestContext.WriteLine("........{0} ...", System.IO.Path.GetFileName(CompressedFile)); if (x == 0) { if (h != 0) { Alienlab.Zlib.GZipStream gzip = compressor as Alienlab.Zlib.GZipStream; if (h % 2 == 1) gzip.FileName = FileToCompress; if (h > 2) gzip.Comment = "Compressing: " + FileToCompress; } } n = -1; while ((n = input.Read(working, 0, working.Length)) != 0) { compressor.Write(working, 0, n); } } finally { if (compressor != null) compressor.Dispose(); } } } // now, decompress with Alienlab.and System.IO.Compression // for (int j = 0; j < 2; j++) for (int j = 1; j >= 0; j--) { using (var input = System.IO.File.OpenRead(CompressedFile)) { Stream decompressor = null; try { int w = k + j * 2; switch (w) { case 0: // k == 0, j == 0 decompressor = new Alienlab.Zlib.GZipStream(input, CompressionMode.Decompress, true); break; case 1: // k == 1, j == 0 decompressor = new Alienlab.Zlib.DeflateStream(input, CompressionMode.Decompress, true); break; case 2: // k == 0, j == 1 decompressor = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress, true); break; case 3: // k == 1, j == 1 decompressor = new System.IO.Compression.DeflateStream(input, System.IO.Compression.CompressionMode.Decompress, true); break; } //TestContext.WriteLine("Decompress: {0} ...", decompressor.GetType().FullName); string DecompressedFile = String.Format("{0}.{1}.decompressed", CompressedFile, (j == 0) ? "Ionic" : "BCL"); TestContext.WriteLine("........{0} ...", System.IO.Path.GetFileName(DecompressedFile)); using (var s2 = System.IO.File.Create(DecompressedFile)) { n = -1; while (n != 0) { n = decompressor.Read(working, 0, working.Length); if (n > 0) s2.Write(working, 0, n); } } int crc2 = DoCrc(DecompressedFile); Assert.AreEqual<UInt32>((UInt32)crc1, (UInt32)crc2); } finally { if (decompressor != null) decompressor.Dispose(); } } } } } } } } TestContext.WriteLine("Done."); }
internal void AddResources(Dictionary<string, byte[]> resources, bool compressedResources) { Tracer.Info(Tracer.Compiler, "CompilerClassLoader adding resources..."); ModuleBuilder moduleBuilder = this.GetTypeWrapperFactory().ModuleBuilder; foreach(KeyValuePair<string, byte[]> kv in resources) { byte[] buf = kv.Value; string name = JVM.MangleResourceName(kv.Key); MemoryStream mem = new MemoryStream(); if(compressedResources) { mem.WriteByte(1); using(System.IO.Compression.DeflateStream def = new System.IO.Compression.DeflateStream(mem, System.IO.Compression.CompressionMode.Compress, true)) { def.Write(buf, 0, buf.Length); } } else { mem.WriteByte(0); mem.Write(buf, 0, buf.Length); } mem.Position = 0; moduleBuilder.DefineManifestResource(name, mem, ResourceAttributes.Public); } }