public static async Task <BA2FileEntryBuilder> Create(BA2FileEntryState state, Stream src, DiskSlabAllocator slab) { var builder = new BA2FileEntryBuilder { _state = state, _rawSize = (int)src.Length, _dataSrc = src }; if (!state.Compressed) { return(builder); } await using (var ms = new MemoryStream()) { await using (var ds = new DeflaterOutputStream(ms)) { ds.IsStreamOwner = false; await builder._dataSrc.CopyToAsync(ds); } builder._dataSrc = slab.Allocate(ms.Length); ms.Position = 0; await ms.CopyToAsync(builder._dataSrc); builder._dataSrc.Position = 0; builder._size = (int)ms.Length; } return(builder); }
/// ファイルを書き込みます。 protected void WriteFile(string type, uint opt0, uint opt1, Stream source) { //Console.WriteLine("taOb extract length {0}", source.Length); MemoryStream dest = new MemoryStream(); using (DeflaterOutputStream gzip = new DeflaterOutputStream(dest)) { gzip.IsStreamOwner = false; byte[] b = new byte[4096]; StreamUtils.Copy(source, gzip, b); } dest.Seek(0, SeekOrigin.Begin); //Console.WriteLine("taOb length {0}", dest.Length); byte[] chunk_type = System.Text.Encoding.ASCII.GetBytes(type); byte[] chunk_data = new byte[dest.Length + 20]; Array.Copy(chunk_type, 0, chunk_data, 0, 4); byte[] buf; buf = BitConverter.GetBytes((UInt32)opt0); Array.Copy(buf, 0, chunk_data, 4, 4); buf = BitConverter.GetBytes((UInt32)opt1); Array.Copy(buf, 0, chunk_data, 8, 4); buf = BitConverter.GetBytes((UInt32)source.Length); Array.Copy(buf, 0, chunk_data, 12, 4); buf = BitConverter.GetBytes((UInt32)dest.Length); Array.Copy(buf, 0, chunk_data, 16, 4); dest.Read(chunk_data, 20, (int)dest.Length); PNGWriter.WriteChunk(writer, "taOb", chunk_data); }
private void openGameBox(string fileName) { IModel model = controller.Model; model.ClearTransientState(); try { model.OpenGameBox(fileName); model.GameLibrary.AddReference(model.CurrentGameBox.Reference); model.CurrentGameBox.OpenBuiltInScenario(model.CurrentGameBox.StartupScenarioFileName); } catch { model.OpenGameBox(model.GameLibrary.DefaultGameBox); model.CurrentGameBox.OpenBuiltInScenario(model.CurrentGameBox.StartupScenarioFileName); throw; } finally { byte[] gameData; using (MemoryStream stream = new MemoryStream()) { using (DeflaterOutputStream compressionStream = new DeflaterOutputStream(stream)) { model.CurrentGameBox.CurrentGame.Save(compressionStream, false); compressionStream.Flush(); } stream.Flush(); gameData = stream.ToArray(); } ++model.StateChangeSequenceNumber; controller.NetworkClient.Send(new GameLoadedMessage(model.StateChangeSequenceNumber, gameData)); controller.View.ResetGraphicsElements(); } }
public void SetPictureData(byte[] pictureData) { base.PictureData = (pictureData); UncompressedSize = (pictureData.Length); // info of chicago project: // "... LZ compression algorithm in the format used by GNU Zip deflate/inflate with a 32k window ..." // not sure what to do, when lookup tables exceed 32k ... try { MemoryStream bos = new MemoryStream(); DeflaterOutputStream dos = new DeflaterOutputStream(bos); dos.Write(pictureData, 0, pictureData.Length); dos.Dispose(); raw_pictureData = bos.ToArray(); } catch (IOException e) { throw new RuntimeException("Can't compress metafile picture data", e); } CompressedSize = (raw_pictureData.Length); IsCompressed = (true); }
/// <summary> /// 数据压缩 /// </summary> /// <param name="data">待压缩数据</param> /// <param name="offset">数据起始位置</param> /// <param name="len">数据长度</param> /// <param name="os">压缩后的数据输出流</param> /// <param name="deflater">压缩器</param> public static void Compress(byte[] data, int offset, int len, Stream os, Deflater deflater) { DeflaterOutputStream dos = new DeflaterOutputStream(os, deflater, 1024 * 4); dos.Write(data, offset, len); dos.Finish(); }
/// <exception cref="System.IO.IOException"/> private static void ProcessExtraSamples(DeflaterOutputStream zip, DeflaterOutputStream mzip, byte[] outBuf , int samplePerPixel, int bitsPerSample, int width, int height) { if (bitsPerSample == 8) { byte[] mask = new byte[width * height]; int mptr = 0; int optr = 0; int total = width * height * samplePerPixel; for (int k = 0; k < total; k += samplePerPixel) { for (int s = 0; s < samplePerPixel - 1; ++s) { outBuf[optr++] = outBuf[k + s]; } mask[mptr++] = outBuf[k + samplePerPixel - 1]; } zip.Write(outBuf, 0, optr); mzip.Write(mask, 0, mptr); } else { throw new iText.IO.IOException(iText.IO.IOException.ExtraSamplesAreNotSupported); } }
public void DeflatorStreamOwnership() { var memStream = new TrackedMemoryStream(); var s = new DeflaterOutputStream(memStream); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); s.Close(); Assert.IsTrue(memStream.IsClosed, "Should be closed after parent owner close"); Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close"); memStream = new TrackedMemoryStream(); s = new DeflaterOutputStream(memStream); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); s.IsStreamOwner = false; s.Close(); Assert.IsFalse(memStream.IsClosed, "Should not be closed after parent owner close"); Assert.IsFalse(memStream.IsDisposed, "Should not be disposed after parent owner close"); }
/// <summary> /// Compresses the specified string to compress. /// </summary> /// <param name="stringToCompress">The string to compress.</param> /// <returns> /// A <see cref="CompressedItem"/> containing details about /// the compressed string. /// </returns> /// <externalUnit cref="CompressedItem"/> /// <externalUnit cref="MemoryStream"/> /// <externalUnit cref="Encoding"/> /// <externalUnit cref="DeflaterOutputStream"/> /// <revision revisor="dev06" date="1/11/2009" version="1.0.0.0"> /// Member Created /// </revision> public static CompressedItem Compress(string stringToCompress) { // create parm for return var compressedItem = new CompressedItem(); // get the bytes of the string byte[] uncompressedData = Encoding.Unicode.GetBytes(stringToCompress); // save the uncompressed size of the byte array to // use when decompressing compressedItem.UncompressedSize = uncompressedData.Length; // create a stream for storing the compressed data using (var compressedStream = new MemoryStream()) { // create stream for compressing the data using (var zipStream = new DeflaterOutputStream(compressedStream)) { // write the data to the stream - which will compress it // and put it it the compressed stream object zipStream.Write( uncompressedData, 0, uncompressedData.Length); } // set the compressed data on the return item compressedItem.Data = compressedStream.ToArray(); } return(compressedItem); }
/// <exception cref="System.IO.IOException"></exception> private byte[] CompressPackFormat(int type, byte[] data) { byte[] hdr = new byte[64]; int rawLength = data.Length; int nextLength = (int)(((uint)rawLength) >> 4); hdr[0] = unchecked ((byte)((nextLength > 0 ? unchecked ((int)(0x80)) : unchecked ((int )(0x00))) | (type << 4) | (rawLength & unchecked ((int)(0x0F))))); rawLength = nextLength; int n = 1; while (rawLength > 0) { nextLength = (int)(((uint)nextLength) >> 7); hdr[n++] = unchecked ((byte)((nextLength > 0 ? unchecked ((int)(0x80)) : unchecked ( (int)(0x00))) | (rawLength & unchecked ((int)(0x7F))))); rawLength = nextLength; } ByteArrayOutputStream @out = new ByteArrayOutputStream(); @out.Write(hdr, 0, n); DeflaterOutputStream d = new DeflaterOutputStream(@out); d.Write(data); d.Finish(); return(@out.ToByteArray()); }
/// <summary> /// Compressed data using the zlib compression library. /// </summary> /// <param name="data">Data to be compressed.</param> /// <param name="gnf">GNF class that is associated with that data.</param> /// <returns>Compressed data</returns> private static byte[] GetCompressedZlibData(byte[] data, GNF gnf) { if (data == null || data.Length == 0) { return(data); } using (var inStream = new MemoryStream(data)) { var outStream = new MemoryStream(); var compressStream = new DeflaterOutputStream(outStream, new Deflater(Deflater.DEFAULT_COMPRESSION)); int bufferSize; var buffer = new byte[4096]; while ((bufferSize = inStream.Read(buffer, 0, buffer.Length)) > 0) { compressStream.Write(buffer, 0, bufferSize); } compressStream.Close(); byte[] outStreamData = outStream.ToArray(); gnf.Size = (uint)outStreamData.Length; return(outStreamData); } }
private bool FlushCompressedBlock() { using (var data = new MemoryStream()) { /*var blockLength = Array.FindLastIndex(this._BlockBytes, this._BlockOffset - 1, b => b != 0); * blockLength = 1 + (blockLength < 0 ? 0 : blockLength);*/ var blockLength = this._BlockOffset; var zlib = new DeflaterOutputStream(data); zlib.Write(this._BlockBytes, 0, blockLength); zlib.Finish(); data.Flush(); var compressedLength = (int)data.Length; if (data.Length < blockLength) { this._BaseStream.WriteValueS32(32 + compressedLength, this._Endian); this._BaseStream.WriteValueU8(1); CompressedBlockHeader compressedBlockHeader; compressedBlockHeader.UncompressedSize = (uint)blockLength; compressedBlockHeader.Unknown04 = 32; compressedBlockHeader.Unknown08 = 81920; compressedBlockHeader.Unknown0C = 135200769; compressedBlockHeader.CompressedSize = (uint)compressedLength; compressedBlockHeader.Unknown14 = 0; compressedBlockHeader.Unknown18 = 0; compressedBlockHeader.Unknown1C = 0; compressedBlockHeader.Write(this._BaseStream, this._Endian); this._BaseStream.Write(data.GetBuffer(), 0, compressedLength); this._BlockOffset = 0; return(true); } } return(false); }
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); }
internal DeflateStream(Stream compressedStream, CompressionMode mode, bool leaveOpen, bool gzip) { if (compressedStream == null) { throw new ArgumentNullException("compressedStream"); } switch (mode) { case CompressionMode.Compress: if (!compressedStream.CanWrite) { throw new ArgumentException("The base stream is not writeable."); } OutputStream outStream = new OutputStreamImpl(compressedStream); _writer = gzip ? new GZIPOutputStream(outStream) : new DeflaterOutputStream(outStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true)); break; case CompressionMode.Decompress: if (!compressedStream.CanRead) { throw new ArgumentException("The base stream is not readable."); } InputStream inStream = new InputStreamImpl(compressedStream); _reader = gzip ? new GZIPInputStream(inStream) : new InflaterInputStream(inStream, new Inflater(true)); break; default: throw new ArgumentException("mode"); } _baseStream = compressedStream; _leaveOpen = leaveOpen; _open = true; }
public override void Run() { var tasks = new Task[options.Threads]; for (var i = 0; i < options.Threads; i++) { var i1 = i; tasks[i] = ThreadAffinity.RunAffinity(1uL << i, () => { using (Stream s = new MemoryStream()) { using var stream = new DeflaterOutputStream(s, new Deflater(Deflater.BEST_COMPRESSION)); using var sw = new StreamWriter(stream); sw.Write(datas[i1]); sw.Flush(); stream.Finish(); } BenchmarkRunner.ReportProgress(); }); } Task.WaitAll(tasks); }
protected void WriteTaOb(BinaryWriter bw, string type, uint opt0, uint opt1, byte[] data) { Console.WriteLine("WriteTaOb {0}", type); Console.WriteLine("taOb extract length {0}", data.Length); byte[] chunk_type = System.Text.Encoding.ASCII.GetBytes(type); MemoryStream dest = new MemoryStream(); using (DeflaterOutputStream gzip = new DeflaterOutputStream(dest)) { gzip.IsStreamOwner = false; gzip.Write(data, 0, data.Length); } dest.Seek(0, SeekOrigin.Begin); Console.WriteLine("taOb length {0}", dest.Length); byte[] chunk_data = new byte[dest.Length + 20]; Array.Copy(chunk_type, 0, chunk_data, 0, 4); byte[] buf; buf = BitConverter.GetBytes((UInt32)opt0); Array.Copy(buf, 0, chunk_data, 4, 4); buf = BitConverter.GetBytes((UInt32)opt1); Array.Copy(buf, 0, chunk_data, 8, 4); buf = BitConverter.GetBytes((UInt32)data.Length); Array.Copy(buf, 0, chunk_data, 12, 4); buf = BitConverter.GetBytes((UInt32)dest.Length); Array.Copy(buf, 0, chunk_data, 16, 4); dest.Read(chunk_data, 20, (int)dest.Length); WriteChunk(bw, "taOb", chunk_data); }
private void CompressData() { if (_bsa.HeaderType == VersionType.SSE) { var r = new MemoryStream(); using (var w = LZ4Stream.Encode(r, new LZ4EncoderSettings() { CompressionLevel = LZ4Level.L10_OPT })) (new MemoryStream(_rawData)).CopyTo(w); _rawData = r.ToArray(); } else if (_bsa.HeaderType == VersionType.FO3 || _bsa.HeaderType == VersionType.TES4) { var r = new MemoryStream(); using (var w = new DeflaterOutputStream(r)) (new MemoryStream(_rawData)).CopyTo(w); _rawData = r.ToArray(); } else { throw new NotImplementedException($"Can't compress data for {_bsa.HeaderType} BSAs."); } }
internal static bool _compress(Stream uncompressed, out byte[] res) { using (MemoryStream result = new MemoryStream()) { if (uncompressed.Length == 0) { res = null; return(false); } BinaryWriter w = new BinaryWriter(result); using (DeflaterOutputStream ds = new DeflaterOutputStream(result) { IsStreamOwner = false }) { uncompressed.CopyTo(ds); } if (result.Length < uncompressed.Length) { res = result.ToArray(); return(true); } else { res = null; return(false); } } }
public static ChunkBuilder Create(BA2DX10EntryState state, ChunkState chunk, Stream src) { var builder = new ChunkBuilder { _chunk = chunk }; using (var ms = new MemoryStream()) { src.CopyToLimit(ms, (int)chunk.FullSz); builder._data = ms.ToArray(); } if (!chunk.Compressed) { return(builder); } using (var ms = new MemoryStream()) { using (var ds = new DeflaterOutputStream(ms)) { ds.Write(builder._data, 0, builder._data.Length); } builder._data = ms.ToArray(); } builder._packSize = (uint)builder._data.Length; return(builder); }
public void CloseDeflatorWithNestedUsing() { 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 txtFile = new StreamWriter(deflator)) { txtFile.Write("Hello"); txtFile.Flush(); } File.Delete(tempFile); }
public static BA2FileEntryBuilder Create(BA2FileEntryState state, Stream src) { var builder = new BA2FileEntryBuilder { _state = state }; using (var ms = new MemoryStream()) { src.CopyTo(ms); builder._data = ms.ToArray(); } builder._rawSize = builder._data.Length; if (state.Compressed) { using (var ms = new MemoryStream()) { using (var ds = new DeflaterOutputStream(ms)) { ds.Write(builder._data, 0, builder._data.Length); } builder._data = ms.ToArray(); } builder._size = builder._data.Length; } return(builder); }
public override void Initialize() { var tasks = new Task[options.Threads]; for (var i = 0; i < options.Threads; i++) { var i1 = i; tasks[i1] = Task.Run(() => { var data = DataGenerator.GenerateString((int)(volume / options.Threads)); using var s = new MemoryStream(); using (var stream = new DeflaterOutputStream(s, new Deflater(Deflater.BEST_COMPRESSION))) { using var sw = new StreamWriter(stream); sw.Write(data); sw.Flush(); stream.Finish(); stream.IsStreamOwner = false; } s.Seek(0, SeekOrigin.Begin); datas[i1] = s.ToArray(); }); } Task.WaitAll(tasks); }
/// <summary> /// 使用zlib压缩一段数据 /// </summary> /// <param name="input"></param> /// <returns></returns> private byte[] compressBuffer(byte[] input) { byte[] result = null; using (MemoryStream outputStream = new MemoryStream()) { using (MemoryStream inputStream = new MemoryStream(input)) { using (DeflaterOutputStream outZStream = new DeflaterOutputStream(outputStream, new Deflater(Deflater.DEFAULT_COMPRESSION))) { try { inputStream.CopyTo(outZStream); outZStream.Flush(); outZStream.Finish(); } finally { outputStream.Seek(0, SeekOrigin.Begin); result = new byte[outputStream.Length]; outputStream.Read(result, 0, (int)outputStream.Length); } } } } return(result); }
/// <summary> /// 数据压缩 /// </summary> /// <param name="s">待压缩数据输入流</param> /// <param name="os">压缩后的数据输出流</param> /// <param name="deflater">压缩器</param> public static void Compress(Stream s, Stream os, Deflater deflater) { DeflaterOutputStream dos = new DeflaterOutputStream(os, deflater, 1024 * 4); Stdio.CopyStream(s, dos); dos.Finish(); }
/// <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(); } } } }
protected override void InternalWriteStream(MemoryStream AStream) { PdfNumber FLength; PdfArray FFilter; MemoryStream TmpStream; FLength = FAttributes.PdfNumberByName("Length"); FFilter = (PdfArray)FAttributes.ValueByName("Filter"); TmpStream = new MemoryStream(); DeflaterOutputStream s = null; if (FFilter.FindName("FlateDecode") != null) { s = new DeflaterOutputStream(TmpStream); byte[] bytedata = FStream.ToArray(); s.Write(bytedata, 0, bytedata.Length); s.Finish(); } else { FStream.WriteTo(TmpStream); } FLength.Value = TmpStream.Length; FAttributes.WriteToStream(AStream); Generic._WriteString("\r\n" + "stream" + "\r\n", AStream); TmpStream.WriteTo(AStream); if (s != null) { s.Close(); } Generic._WriteString("\n" + "endstream", AStream); }
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); }
// 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; }
/// <summary> /// Encodes the specified data. /// </summary> public byte[] Encode(byte[] data, PdfFlateEncodeMode mode) { MemoryStream ms = new MemoryStream(); // DeflateStream/GZipStream does not work immediately and I have not the leisure to work it out. // So I keep on using SharpZipLib even with .NET 2.0. int level = Deflater.DEFAULT_COMPRESSION; switch (mode) { case PdfFlateEncodeMode.BestCompression: level = Deflater.BEST_COMPRESSION; break; case PdfFlateEncodeMode.BestSpeed: level = Deflater.BEST_SPEED; break; } DeflaterOutputStream zip = new DeflaterOutputStream(ms, new Deflater(level, false)); zip.Write(data, 0, data.Length); zip.Finish(); return(ms.ToArray()); }
public static async Task <ChunkBuilder> Create(BA2DX10EntryState state, ChunkState chunk, Stream src, DiskSlabAllocator slab) { var builder = new ChunkBuilder { _chunk = chunk }; if (!chunk.Compressed) { builder._dataSlab = slab.Allocate(chunk.FullSz); await src.CopyToWithStatusAsync((int)chunk.FullSz, builder._dataSlab, $"Writing {state.Path} {chunk.StartMip}:{chunk.EndMip}"); } else { var deflater = new Deflater(Deflater.BEST_COMPRESSION); await using var ms = new MemoryStream(); await using (var ds = new DeflaterOutputStream(ms, deflater)) { ds.IsStreamOwner = false; await src.CopyToWithStatusAsync((int)chunk.FullSz, ds, $"Compressing {state.Path} {chunk.StartMip}:{chunk.EndMip}"); } builder._dataSlab = slab.Allocate(ms.Length); ms.Position = 0; await ms.CopyToWithStatusAsync(ms.Length, builder._dataSlab, $"Writing {state.Path} {chunk.StartMip}:{chunk.EndMip}"); builder._packSize = (uint)ms.Length; } builder._dataSlab.Position = 0; return(builder); }
private static byte[] Compress(byte[] data) { byte[] array; try { Deflater deflater = new Deflater(); MemoryStream memoryStream = new MemoryStream(data.Length); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(memoryStream, deflater); deflaterOutputStream.Write(data, 0, data.Length); deflaterOutputStream.Flush(); deflaterOutputStream.Finish(); array = memoryStream.ToArray(); } catch (Exception) { return(null); } byte[] bytes = BitConverter.GetBytes((ulong)((long)data.Length)); int num = array.Length + FileUtil.BNET_COMPRESSED_HEADER_SIZE; byte[] array2 = new byte[num]; int num2 = 0; Array.Copy(FileUtil.BNET_COMPRESSED_MAGIC_BYTES, 0, array2, num2, FileUtil.BNET_COMPRESSED_MAGIC_BYTES.Length); num2 += FileUtil.BNET_COMPRESSED_MAGIC_BYTES.Length; Array.Copy(FileUtil.BNET_COMPRESSED_VERSION_BYTES, 0, array2, num2, FileUtil.BNET_COMPRESSED_VERSION_BYTES.Length); num2 += FileUtil.BNET_COMPRESSED_VERSION_BYTES.Length; Array.Copy(bytes, 0, array2, num2, bytes.Length); num2 += bytes.Length; Array.Copy(array, 0, array2, num2, array.Length); return(array2); }
/// <summary> /// SharpZipѹËõ /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static byte[] CompressSharpZip(byte[] buffer) { if (buffer == null || buffer.Length == 0) { return buffer; } using (MemoryStream inStream = new MemoryStream(buffer)) { MemoryStream outStream = new MemoryStream(); Deflater mDeflater = new Deflater(Deflater.BEST_COMPRESSION); DeflaterOutputStream compressStream = new DeflaterOutputStream(outStream, mDeflater); int mSize; byte[] mWriteData = new Byte[4096]; while ((mSize = inStream.Read(mWriteData, 0, 4096)) > 0) { compressStream.Write(mWriteData, 0, mSize); } compressStream.Finish(); inStream.Close(); return outStream.ToArray(); } }
/// <summary> /// Get an output stream for the specified <see cref="BlubbEntry"/> /// </summary> /// <param name="entry">The entry to get an output stream for.</param> /// <returns>The output stream obtained for the entry.</returns> Stream GetOutputStream( BlubbZipEntry entry ) { Stream result = baseStream_; if( entry.IsCrypted == true ) { result = CreateAndInitEncryptionStream( result, entry ); } switch( entry.CompressionMethod ) { case CompressionMethod.Stored: result = new UncompressedStream( result ); break; case CompressionMethod.Deflated: DeflaterOutputStream dos = new DeflaterOutputStream( result, new Deflater( 9, true ) ); dos.IsStreamOwner = false; result = dos; break; default: throw new BlubbZipException( "Unknown compression method " + entry.CompressionMethod ); } return result; }
/// <summary> /// Get an output stream for the specified <see cref="ZipEntry"/> /// </summary> /// <param name="entry">The entry to get an output stream for.</param> /// <returns>The output stream obtained for the entry.</returns> Stream GetOutputStream(ZipEntry entry) { Stream result = baseStream_; if ( entry.IsCrypted == true ) { #if NETCF_1_0 throw new ZipException("Encryption not supported for Compact Framework 1.0"); #else result = CreateAndInitEncryptionStream(result, entry); #endif } switch ( entry.CompressionMethod ) { case CompressionMethod.Stored: result = new UncompressedStream(result); break; case CompressionMethod.Deflated: DeflaterOutputStream dos = new DeflaterOutputStream(result, new Deflater(9, true)); dos.IsStreamOwner = false; result = dos; break; default: throw new ZipException("Unknown compression method " + entry.CompressionMethod); } return result; }