public byte[] Compress(byte[] bytData, params int[] ratio) { int compRatio = 9; try { if (ratio[0] > 0) { compRatio = ratio[0]; } } catch { throw; } try { var ms = new MemoryStream(); var defl = new Deflater(compRatio, false); Stream s = new DeflaterOutputStream(ms, defl); s.Write(bytData, 0, bytData.Length); s.Close(); byte[] compressedData = ms.ToArray(); return compressedData; } catch { throw; } }
public void CloseInflatorWithNestedUsing() { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { string tempFile = Environment.TickCount.ToString(); store.CreateDirectory(tempFile); tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); using (IsolatedStorageFileStream diskFile = store.CreateFile(tempFile)) using (DeflaterOutputStream deflator = new DeflaterOutputStream(diskFile)) using (StreamWriter textWriter = new StreamWriter(deflator)) { textWriter.Write("Hello"); textWriter.Flush(); } using (IsolatedStorageFileStream diskFile = store.OpenFile(tempFile, FileMode.Open)) using (InflaterInputStream deflator = new InflaterInputStream(diskFile)) using (StreamReader textReader = new StreamReader(deflator)) { char[] buffer = new char[5]; int readCount = textReader.Read(buffer, 0, 5); Assert.AreEqual(5, readCount); StringBuilder b = new StringBuilder(); b.Append(buffer); Assert.AreEqual("Hello", b.ToString()); } store.CreateFile(tempFile); } }
public void CloseDeflatorWithNestedUsing() { string tempFile = null; try { tempFile = Path.GetTempPath(); } catch (SecurityException) { } Assert.IsNotNull(tempFile, "No permission to execute this test?"); if (tempFile != null) { tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); using (FileStream diskFile = File.Create(tempFile)) using (DeflaterOutputStream deflator = new DeflaterOutputStream(diskFile)) using (StreamWriter txtFile = new StreamWriter(deflator)) { txtFile.Write("Hello"); txtFile.Flush(); } File.Delete(tempFile); } }
/// <summary> /// Compresses a string. /// </summary> /// <param name="value">The string to compress.</param> /// <returns>The compressed string.</returns> public string CompressString(string value) { // The input value must be non-null if (value == null) { throw new ArgumentNullException("value"); } var outputData = string.Empty; var inputData = UTF8Encoding.UTF8.GetBytes(value); using (var inputStream = new MemoryStream(inputData)) { using (var outputStream = new MemoryStream()) { // Zip the string using (var zipStream = new DeflaterOutputStream(outputStream)) { zipStream.IsStreamOwner = false; StreamUtils.Copy(inputStream, zipStream, new byte[4096]); } // Convert to a string outputData = Convert.ToBase64String(outputStream.GetBuffer(), 0, Convert.ToInt32(outputStream.Length)); } } // Return the compressed string return outputData; }
// 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; }
public void TestInflateDeflate() { MemoryStream ms = new MemoryStream(); Deflater deflater = new Deflater(6); DeflaterOutputStream outStream = new DeflaterOutputStream(ms, deflater); byte[] buf = new byte[1000000]; System.Random rnd = new Random(); rnd.NextBytes(buf); outStream.Write(buf, 0, buf.Length); outStream.Flush(); outStream.Finish(); ms.Seek(0, SeekOrigin.Begin); InflaterInputStream inStream = new InflaterInputStream(ms); byte[] buf2 = new byte[buf.Length]; int pos = 0; while (true) { int numRead = inStream.Read(buf2, pos, 4096); if (numRead <= 0) { break; } pos += numRead; } for (int i = 0; i < buf.Length; ++i) { Assertion.AssertEquals(buf2[i], buf[i]); } }
public void CloseInflatorWithNestedUsing() { string tempFile = null; try { tempFile = Path.GetTempPath(); } catch (SecurityException) { } Assert.IsNotNull(tempFile, "No permission to execute this test?"); tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); using (FileStream diskFile = File.Create(tempFile)) using (DeflaterOutputStream deflator = new DeflaterOutputStream(diskFile)) using (StreamWriter textWriter = new StreamWriter(deflator)) { textWriter.Write("Hello"); textWriter.Flush(); } using (FileStream diskFile = File.OpenRead(tempFile)) using (InflaterInputStream deflator = new InflaterInputStream(diskFile)) using (StreamReader textReader = new StreamReader(deflator)) { char[] buffer = new char[5]; int readCount = textReader.Read(buffer, 0, 5); Assert.AreEqual(5, readCount); var b = new StringBuilder(); b.Append(buffer); Assert.AreEqual("Hello", b.ToString()); } File.Delete(tempFile); }
public static byte[] CompressZlib(byte[] input) { MemoryStream m = new MemoryStream(); DeflaterOutputStream zipStream = new DeflaterOutputStream(m, new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(8)); zipStream.Write(input, 0, input.Length); zipStream.Finish(); return m.ToArray(); }
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(); }
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(); }
public ZlibOutputStreamIs(Stream st, int compressLevel, EDeflateCompressStrategy strat, bool leaveOpen) : base(st,compressLevel,strat,leaveOpen) { deflater=new Deflater(compressLevel); setStrat(strat); ost = new DeflaterOutputStream(st, deflater); ost.IsStreamOwner = !leaveOpen; }
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(); }
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(); }
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); }
/// <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()); }
/// <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(); }
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; }
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; }
MemoryStream Deflate(byte[] data, int level, bool zlib) { MemoryStream memoryStream = new MemoryStream(); Deflater deflater = new Deflater(level, !zlib); using ( DeflaterOutputStream outStream = new DeflaterOutputStream(memoryStream, deflater) ) { outStream.IsStreamOwner = false; outStream.Write(data, 0, data.Length); outStream.Flush(); outStream.Finish(); } return memoryStream; }
public static void Serialize(Stream stream, PiaFile piaFile) { if (stream == null) throw new ArgumentNullException("Stream"); if (piaFile == null) throw new ArgumentNullException("PiaFile"); try { // Header var headerString = piaFile.Header.ToString(); var headerBytes = Encoding.Default.GetBytes(headerString); stream.Write(headerBytes, 0, headerBytes.Length); // Nodes var nodeString = _serializeNode(piaFile); var nodeBytes = Encoding.Default.GetBytes(nodeString); // Deflation byte[] deflatedBytes; var deflater = new Deflater(Deflater.DEFAULT_COMPRESSION); using (var ms = new MemoryStream()) { var deflateStream = new DeflaterOutputStream(ms, deflater); deflateStream.Write(nodeBytes, 0, nodeBytes.Length); deflateStream.Finish(); deflatedBytes = ms.ToArray(); } // Checksum var checkSum = new byte[12]; BitConverter.GetBytes(deflater.Adler).CopyTo(checkSum, 0); // Adler BitConverter.GetBytes(nodeBytes.Length).CopyTo(checkSum, 4); // InflatedSize BitConverter.GetBytes(deflatedBytes.Length).CopyTo(checkSum, 8); // DeflatedSize stream.Write(checkSum, 0, checkSum.Length); // Final write stream.Write(deflatedBytes, 0, deflatedBytes.Length); } catch (Exception) { throw; } }
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; } }
/* * Name function: Compress * Purpose: compress a part of the byte array into a Zlib Block * Input: - buffer: byte array * - offset: starting offset inside the array * - count: num of bytes to compress starting from the offset * Output: compressed byte array block, the structure is: * - magic word * - max segment size * - total compressed size * - total uncompressed size * - segment list * - compressed data list */ public static byte[] Compress(byte[] buffer, int offset, int count) { if(buffer == null) throw new ArgumentNullException(); if (count < 0) throw new FormatException(); if (offset + count > buffer.Length) throw new IndexOutOfRangeException(); MemoryStream headBlock = new MemoryStream(); MemoryStream dataBlock = new MemoryStream(); DeflaterOutputStream zipStream; int numSeg = (int)Math.Ceiling((double)count / (double)maxSegmentSize); headBlock.WriteValueU32(magic); headBlock.WriteValueU32(maxSegmentSize); headBlock.WriteValueU32(0x0); //total compressed size, still to calculate headBlock.WriteValueS32(count); //total uncompressed size for (int i = count; i > 0; i -= (int)maxSegmentSize) { int copyBytes = Math.Min(i, (int)maxSegmentSize); uint precCompSize = (uint)dataBlock.Length; zipStream = new DeflaterOutputStream(dataBlock); zipStream.Write(buffer, offset + (count - i), copyBytes); zipStream.Flush(); zipStream.Finish(); headBlock.WriteValueU32((uint)dataBlock.Length - precCompSize); //compressed segment size headBlock.WriteValueS32(copyBytes); //uncompressed segment size //Console.WriteLine(" Segment size: {0}, total read: {1}, compr size: {2}", maxSegmentSize, copyBytes, (uint)dataBlock.Length - precCompSize); } headBlock.Seek(8, SeekOrigin.Begin); headBlock.WriteValueS32((int)dataBlock.Length); // total compressed size byte[] finalBlock = new byte[headBlock.Length + dataBlock.Length]; Buffer.BlockCopy(headBlock.ToArray(), 0, finalBlock, 0, (int)headBlock.Length); Buffer.BlockCopy(dataBlock.ToArray(), 0, finalBlock, (int)headBlock.Length, (int)dataBlock.Length); headBlock.Close(); dataBlock.Close(); return finalBlock; }
public static string Compress(byte[] data) { using(var m = new MemoryStream()) { switch(technique) { case "ZipStream": var br = new BinaryWriter(m); var z = new DeflaterOutputStream(m); br.Write(data.Length); z.Write(data, 0, data.Length); z.Flush(); z.Close(); break; } return technique + ":" + Convert.ToBase64String(m.GetBuffer()); } }
public void CloseDeflatorWithNestedUsing() { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { string tempFile = Environment.TickCount.ToString(); store.CreateDirectory(tempFile); tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); using (IsolatedStorageFileStream diskFile = store.CreateFile(tempFile)) using (DeflaterOutputStream deflator = new DeflaterOutputStream(diskFile)) using (StreamWriter txtFile = new StreamWriter(deflator)) { txtFile.Write("Hello"); txtFile.Flush(); } store.CreateFile(tempFile); } }
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; } } }
/// <summary> /// Write out bytes to the underlying stream after compressing them using deflate /// </summary> /// <param name="buffer">The array of bytes to write</param> /// <param name="offset">The offset into the supplied buffer to start</param> /// <param name="count">The number of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) { if (m_stream == null) { Deflater deflater; switch(CompressionLevel) { case CompressionLevels.High: deflater = new Deflater(Deflater.BEST_COMPRESSION, true); break; case CompressionLevels.Low: deflater = new Deflater(Deflater.BEST_SPEED, true); break; case CompressionLevels.Normal: default: deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true); break; } m_stream = new DeflaterOutputStream(BaseStream, deflater); } m_stream.Write(buffer, offset, count); }
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()); } }
public static int Deflate(byte[] inBuffer, ref byte[] outBuffer) { int newLen = 0, flagOffset = 1; outBuffer[0] = inBuffer[0]; if (inBuffer[0] == 0) { flagOffset = 2; outBuffer[1] = inBuffer[1]; } if (inBuffer.Length > 30) { using (MemoryStream ms = new MemoryStream()) { Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, false); using (DeflaterOutputStream outStream = new DeflaterOutputStream(ms, deflater)) { outStream.IsStreamOwner = false; outStream.Write(inBuffer, flagOffset, inBuffer.Length - flagOffset); outStream.Flush(); outStream.Finish(); } ms.Position = 0; ms.Read(outBuffer, flagOffset + 1, (int)ms.Length); newLen = (int)ms.Length + flagOffset + 1; outBuffer[flagOffset] = 0x5a; } } else { Buffer.BlockCopy(inBuffer, flagOffset, outBuffer, flagOffset + 1, inBuffer.Length - flagOffset); outBuffer[flagOffset] = 0xa5; newLen = inBuffer.Length + 1; } return newLen; }
/// <summary> /// Compresses data using zlib. /// </summary> /// <param name="data">The data to compress</param> /// <returns>A byte array containing the compressed data</returns> public static byte[] Compress(string data) { // Commented out below as it loses extended ASCII (127+) and replaces with a ? // byte[] bytes = ASCIIEncoding.ASCII.GetBytes(data); // Encoding using default terminal extended ascii codepage 437 byte[] bytes = Encoding.GetEncoding(437).GetBytes(data); byte[] returnBytes; using (var stream = new MemoryStream()) { using (var compressedStream = new DeflaterOutputStream(stream)) { compressedStream.Write(bytes, 0, bytes.Length); compressedStream.Finish(); stream.Position = 0; returnBytes = new byte[stream.Length]; stream.Read(returnBytes, 0, returnBytes.Length); } } return returnBytes; }
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); }