public void WriteBitmap(Bitmap b) { if (disposed) { throw new ObjectDisposedException(GetType().FullName); } if (b.Width != Width) { throw new ArgumentException(String.Format("The width of the supplied bitmap ({0}) must match the width of the output png ({1}).", b.Width, Width)); } BitmapData bData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); byte[] data = new byte[b.Width * b.Height * 4]; Marshal.Copy(bData.Scan0, data, 0, data.Length); b.UnlockBits(bData); if (dstream == null) { dstream = new DataStream(); } if (zstream == null) { zstream = new ZlibStream(dstream, CompressionMode.Compress); } byte[] filterType = new byte[] { 0 }; //none byte[] pixel = new byte[4]; int lineWidth = b.Width * 4; for (int y = 0; y < b.Height; y++) { zstream.Write(filterType, 0, 1); for (int x = 0; x < b.Width; x++) { int offset = y * lineWidth + x * 4; //needs to be rgba if (BitConverter.IsLittleEndian) { pixel[2] = data[offset]; //b pixel[1] = data[offset + 1]; //g pixel[0] = data[offset + 2]; //r pixel[3] = data[offset + 3]; //a } else { pixel[3] = data[offset]; //a pixel[0] = data[offset + 1]; //r pixel[1] = data[offset + 2]; //g pixel[2] = data[offset + 3]; //b } zstream.Write(pixel, 0, 4); } } zstream.Flush(); WriteChunk("IDAT", dstream.GetDataSoFar()); }
/// <summary> /// Compresses the input buffer using Zlib /// </summary> /// <param name="decompressedData">Data to be compressed</param> /// <returns>Zlib compressed buffer</returns> public static byte[] CompressData(byte[] decompressedData) { // Create a new memory stream for the input dat. using (MemoryStream input = new MemoryStream(decompressedData)) { // Create a new memory stream for the output data. using (var raw = new MemoryStream()) { // Create the zlib compressor. using (Stream compressor = new ZlibStream(raw, Ionic.Zlib.CompressionMode.Compress)) { byte[] buffer = new byte[4096]; int n; // Loop and compress all of the data in blocks. while ((n = input.Read(buffer, 0, buffer.Length)) != 0) { compressor.Write(buffer, 0, n); } } // Return the compressed data as a byte array. return(raw.ToArray()); } } }
//streamは読み取り開始位置へSeek済みであること public static byte[] ZlibDecompress(MemoryStream stream, int originalSize, int compressedSize) { #if false byte[] data = new byte[compressedSize]; stream.Read(data, 0, data.Length); return(ZlibStream.UncompressBuffer(data)); #else byte[] decompressed = new byte[originalSize]; byte[] buf = new byte[4096]; int remain = compressedSize; using (MemoryStream toStream = new MemoryStream(decompressed)) { using (ZlibStream zlibStream = new ZlibStream(toStream, CompressionMode.Decompress)) { while (remain > 0) { int count = (remain > buf.Length) ? buf.Length : remain; stream.Read(buf, 0, count); zlibStream.Write(buf, 0, count); remain -= count; } } } return(decompressed); #endif }
/// <summary> /// Decompresses buffer into stream. /// </summary> /// <param name="buffer"></param> /// <param name="outStream"></param> private void Decompress(byte[] buffer, Stream outStream) { using (var zlib = new ZlibStream(outStream, CompressionMode.Decompress)) { zlib.Write(buffer, 0, buffer.Length); } }
public void Should_compress_and_decompress_using_supported_library() { var text = "Interoperability is so much fun!"; using var output = new MemoryStream(); using (var compressOutput = new ZlibStream(output, CompressionMode.Compress)) { compressOutput.Write(Encoding.UTF8.GetBytes(text)); compressOutput.Flush(); } output.Flush(); var bytes = output.ToArray(); using var input = new MemoryStream(bytes); using var decompressStream = new InflaterInputStream(input); var buffer = new byte[16384]; var length = decompressStream.Read(buffer, 0, buffer.Length); var result = Encoding.UTF8.GetString(buffer, 0, length); Assert.That(result, Is.EqualTo(text)); }
public void compressTextureFlags(int compFlag) { if (compFlag == 0) { //uncompressed compressedData = (byte[])(uncompressedData.Clone()); } else if (((CompressionTypesPackage)compFlag & CompressionTypesPackage.ZLIB) > 0) { try { var byteStream = new MemoryStream(); var outStream = new ZlibStream(byteStream, CompressionMode.Compress); outStream.Write(uncompressedData, 0, uncompressedData.Length); compressedData = byteStream.GetBuffer(); } catch (Exception e) { logger.Error(e); } } else if (((CompressionTypesPackage)compFlag & CompressionTypesPackage.LZX) > 0) { logger.Error("Found COMPRESS_LZX, unsupported!"); } else if (((CompressionTypesPackage)compFlag & CompressionTypesPackage.LZO) > 0) { lock (lockObject) { compressedData = lzo.Compress(uncompressedData, false); } } compressedSize = compressedData.Length; }
public static void WriteZLIBFile(string fileName, CompoundTag tag, ByteOrder order = ByteOrder.Little) { using (NBTStream stream = new NBTStream(order)) { tag.Write(stream); int sum = 0; using (MemoryStream ms = new MemoryStream()) { ms.WriteByte(0x78); ms.WriteByte(0x01); using (ZlibStream zlib = new ZlibStream(ms, CompressionMode.Compress, true)) { zlib.Write(stream.ToArray(), 0, (int)stream.Length); sum = zlib.Checksum; } byte[] sumBytes = BitConverter.GetBytes(sum); if (BitConverter.IsLittleEndian) { Array.Reverse(sumBytes); } ms.Write(sumBytes, 0, sumBytes.Length); File.WriteAllBytes(fileName, ms.ToArray()); } } }
public static byte[] Compress(this byte[] uncompressed, int level) { if (level == 0) { return(uncompressed); } byte[] result; using (var ms = new MemoryStream()) { using (var compressor = new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.Level0 + level)) compressor.Write(uncompressed, 0, uncompressed.Length); result = ms.ToArray(); } // If compression did not improve the situation, then use // uncompressed bytes. if (result.Length >= uncompressed.Length) { return(uncompressed); } return(result); }
private void Encode_ZLIB() { MemoryStream bs = new MemoryStream(); bs.WriteByte(0x78); WriteCompressionLevel(bs); int sum = 0; using (ZlibStream ds = new ZlibStream(bs, this.CompressionLevel, true)) { ds.Write(this.Payload, 0, this.Payload.Length); sum = ds.Checksum; } byte[] checksumBytes = BitConverter.GetBytes(sum); if (BitConverter.IsLittleEndian) { Array.Reverse(checksumBytes); } bs.Write(checksumBytes, 0, checksumBytes.Length); this.Payload = bs.GetBuffer(); bs.Close(); }
public void GetData(Stream stream, BinaryReader reader, bool compressed = false) { reader.BaseStream.Seek(DataOffset + DataHeaderSize, SeekOrigin.Begin); if (!DataCompressed || compressed) { for (var i = CompressedDataSize; i > 0; i -= Buffer.Length) { var size = i > Buffer.Length ? Buffer.Length : i; reader.Read(Buffer, 0, size); stream.Write(Buffer, 0, size); } } else { using var zlibStream = new ZlibStream(stream, CompressionMode.Decompress); for (var i = CompressedDataSize; i > 0; i -= Buffer.Length) { var size = i > Buffer.Length ? Buffer.Length : i; reader.Read(Buffer, 0, size); zlibStream.Write(Buffer, 0, size); } } }
/// <summary> /// Send an infocard update to the client using the dsace protocol. /// </summary> /// <param name="player"></param> /// <param name="id"></param> /// <param name="text"></param> public static void SendInfocardUpdate(Player player, uint id, string text) { var isrc = new byte[0]; FLMsgType.AddUInt32(ref isrc, 0); // reset all cards flag FLMsgType.AddUInt32(ref isrc, 1); // number of infocards FLMsgType.AddUInt32(ref isrc, id); // id number FLMsgType.AddUnicodeStringLen32(ref isrc, text); // unicode text array with size as uint // Compress the infocard list byte[] idest; using (var ms = new MemoryStream()) { using (var zs = new ZlibStream(ms, CompressionMode.Compress)) zs.Write(isrc, 0, isrc.Length); idest = ms.ToArray(); } // Pack the compressed infocards into the dsac command. var command = new byte[0]; FLMsgType.AddUInt32(ref command, 0xD5AC); FLMsgType.AddUInt32(ref command, 0x01); FLMsgType.AddUInt32(ref command, (uint)idest.Length); FLMsgType.AddUInt32(ref command, (uint)isrc.Length); FLMsgType.AddArray(ref command, idest); SendChat(player, command); }
private static bool Compress(byte[] data, int max, out byte[] compressed) { compressed = null; var level = CompressionLevel.Level4; ReTry: using (var tempMemoryStream = new MemoryStream()) { using (var zipStream = new ZlibStream(tempMemoryStream, CompressionMode.Compress, level)) { zipStream.Write(data, 0, data.Length); } compressed = tempMemoryStream.ToArray(); } if (compressed.Length > max) { if (level == CompressionLevel.BestCompression) { return(false); } level = (CompressionLevel)(level + 1); Debug.WriteLine(string.Format("- Retry {0}", level)); goto ReTry; } return(true); }
/// <summary> /// Compress data using GZip (the retunred buffer will be WITHOUT HEADER) /// </summary> /// <param name="dataToCompress">The stream that hold the data</param> /// <returns>Bytes array of compressed data WITHOUT HEADER bytes</returns> public static byte[] Compress(Stream dataToCompress) { /*using (var compressed = new MemoryStream()) * { * using (var compressor = new System.IO.Compression.GZipStream(compressed, * System.IO.Compression.CompressionMode.Compress)) * { * dataToCompress.CopyTo(compressor); * } * // Get the compressed bytes only after closing the GZipStream * return compressed.ToArray(); * }*/ using (var compressedOutput = new MemoryStream()) { using (var compressedStream = new ZlibStream(compressedOutput, Ionic.Zlib.CompressionMode.Compress, CompressionLevel.Default, false)) { var buffer = new byte[4096]; int byteCount; do { byteCount = dataToCompress.Read(buffer, 0, buffer.Length); if (byteCount > 0) { compressedStream.Write(buffer, 0, byteCount); } } while (byteCount > 0); } return(compressedOutput.ToArray()); } }
public static byte[] DeCompress(byte[] raw) { byte[] result; using (MemoryStream memoryStream = new MemoryStream()) { using (ZlibStream zlibStream = new ZlibStream(memoryStream, Ionic.Zlib.CompressionMode.Decompress)) { zlibStream.Write(raw, 0, raw.Length); } result = memoryStream.ToArray(); } return(result); /* public static byte[] DeCompress(byte[] raw) * { * byte[] result; * using (MemoryStream memoryStream = new MemoryStream()) * { * var a = new zlib.ZOutputStream(memoryStream); * a.Write(raw, 0, raw.Length); * result = memoryStream.ToArray(); * } * return result; * }*/ }
private void NextBlock() { MemoryStream compressed = new MemoryStream(); using (ZlibStream compStream = new ZlibStream(compressed, CompressionMode.Compress, true)) { compStream.Write(_currentBlock, 0, _currentOffset); } byte[] writeData; ushort writeLen; if (compressed.Length < _currentOffset) { writeData = compressed.ToArray(); writeLen = (ushort)compressed.Length; } else { writeData = _currentBlock; writeLen = (ushort)(_currentOffset | 0x8000); } byte[] header = new byte[2]; Utilities.WriteBytesLittleEndian(writeLen, header, 0); _buffer.Write(header, 0, 2); _buffer.Write(writeData, 0, writeLen & 0x7FFF); ++_currentBlockNum; }
/// <summary> /// Writes a block of file data, possibly compressing it. /// </summary> /// <param name="buffer">The data to write.</param> /// <param name="offset">Offset of the first byte to write.</param> /// <param name="count">The number of bytes to write.</param> /// <returns> /// The 'length' of the (possibly compressed) data written, including /// a flag indicating compression (or not). /// </returns> private uint WriteDataBlock(byte[] buffer, int offset, int count) { MemoryStream compressed = new MemoryStream(); using (ZlibStream compStream = new ZlibStream(compressed, CompressionMode.Compress, true)) { compStream.Write(buffer, offset, count); } byte[] writeData; int writeOffset; int writeLen; if (compressed.Length < count) { writeData = compressed.ToArray(); writeOffset = 0; writeLen = (int)compressed.Length; } else { writeData = buffer; writeOffset = offset; writeLen = count | 0x01000000; } _context.RawStream.Write(writeData, writeOffset, writeLen & 0xFFFFFF); return((uint)writeLen); }
/// <summary> /// Compresses a byte array using the specified compression type. /// </summary> /// <param name="bytes">The byte array to be compressed.</param> /// <param name="level">Amount of compression to use.</param> /// <param name="type">Type of compression to use.</param> /// <returns>Compressed byte array.</returns> public static byte[] Compress(this byte[] bytes, CompressionLevel level, CompressionType type) { using (MemoryStream memory = new MemoryStream()) { switch (type) { case CompressionType.Zlib: using (ZlibStream stream = new ZlibStream(memory, CompressionMode.Compress, level, true)) stream.Write(bytes, 0, bytes.Length); break; case CompressionType.GZip: using (GZipStream stream = new GZipStream(memory, CompressionMode.Compress, level, true)) stream.Write(bytes, 0, bytes.Length); break; default: throw new ArgumentException("Unknown compression type."); } memory.Position = 0; bytes = new byte[memory.Length]; memory.Read(bytes, 0, (int)memory.Length); } return(bytes); }
/// <summary> /// 解凍 /// </summary> public byte[] Inflate(int contentIndex) { int offset = SZipHeader.Size + _header.CompressedContentHeaderTableSize + _header.CompressedContentNameTableSize; for (int i = 0; i < contentIndex; i++) { offset += _contents[i].CompressedDataSize; } _stream.Seek(offset, SeekOrigin.Begin); byte[] buf = new byte[4 * 1024]; byte[] uncompressed = new byte[_contents[contentIndex].OriginalDataSize]; int remain = _contents[contentIndex].CompressedDataSize; using (MemoryStream toStram = new MemoryStream(uncompressed)) { using (ZlibStream zlibStream = new ZlibStream(toStram, CompressionMode.Decompress)) { while (remain > 0) { int count = (remain > buf.Length) ? buf.Length : remain; _stream.Read(buf, 0, count); zlibStream.Write(buf, 0, count); remain -= count; } } } return(uncompressed); }
public void TestInvalidChecksum() { byte[] testData = Encoding.ASCII.GetBytes("This is a test string"); MemoryStream compressedStream = new MemoryStream(); using (ZlibStream zs = new ZlibStream(compressedStream, CompressionMode.Compress, true)) { zs.Write(testData, 0, testData.Length); } compressedStream.Seek(-2, SeekOrigin.End); compressedStream.Write(new byte[] { 0, 0 }, 0, 2); compressedStream.Position = 0; Assert.Throws <InvalidDataException>(() => { using (ZlibStream uzs = new ZlibStream(compressedStream, CompressionMode.Decompress, true)) { byte[] outData = new byte[testData.Length]; uzs.Read(outData, 0, outData.Length); Assert.Equal(testData, outData); // Should be end of stream Assert.Equal(-1, uzs.ReadByte()); } }); }
private static void Unzip(byte[] compressed, int start, int count) { using (ZlibStream deCompressor = new ZlibStream(unzipOut, CompressionMode.Decompress, CompressionLevel.Default, true)) { deCompressor.Write(compressed, start, count); } }
private static void Zip(byte[] buffer, int start, int count) { using (ZlibStream compressor = new ZlibStream(zipOut, CompressionMode.Compress, CompressionLevel.Default, true)) { compressor.Write(buffer, start, count); } }
/// <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()) { ZlibStream deflaterOutputStream = new ZlibStream(out1, CompressionMode.Compress); 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(); } } } }
private static byte[] Compress(Hash hash, byte[] data) { byte[] result = null; using (var ms = new MemoryStream()) using (var writer = new BinaryWriter(ms)) { var sw = Stopwatch.StartNew(); using (var msCompress = new MemoryStream()) { using (var zs = new ZlibStream(msCompress, CompressionMode.Compress, CompressionLevel.None)) { zs.Write(data, 0, data.Length); } var compressed = msCompress.ToArray(); writer.Write(data.Length); writer.Write(compressed); result = ms.ToArray(); sw.Stop(); Debug.WriteLine(string.Format("Compression : {0:N0} -> {1:N0} - {2} ms ", data.Length, compressed.Length, sw.ElapsedMilliseconds)); } } DecryptionUtility.Decrypt(result, 0, result.Length, ref hash); return(result); }
private static byte[] Compress(byte[] data, int originalSize) { var level = CompressionLevel.Default; ReTry: using (var ms = new MemoryStream()) { using (var stream = new ZlibStream(ms, CompressionMode.Compress, level)) { stream.Write(data, 0, data.Length); } var compressed = ms.ToArray(); if (compressed.Length > originalSize) { if (level < CompressionLevel.BestCompression) { level = (level + 1); goto ReTry; } else { return(null); } } return(compressed); } }
public void Compress(string algorithm) { if (algorithm == CompressionAlgorithm.Deflate) { byte[] buffer = _memoryStream.ToArray(); MemoryStream ms = new MemoryStream(); DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Compress, true); deflateStream.Write(buffer, 0, buffer.Length); deflateStream.Close(); _memoryStream.Close(); _memoryStream = ms; AMFReader amfReader = new AMFReader(_memoryStream); AMFWriter amfWriter = new AMFWriter(_memoryStream); _dataOutput = new DataOutput(amfWriter); _dataInput = new DataInput(amfReader); } if (algorithm == CompressionAlgorithm.Zlib) { byte[] buffer = _memoryStream.ToArray(); MemoryStream ms = new MemoryStream(); ZlibStream zlibStream = new ZlibStream(ms, CompressionMode.Compress, true); zlibStream.Write(buffer, 0, buffer.Length); zlibStream.Flush(); zlibStream.Close(); zlibStream.Dispose(); _memoryStream.Close(); _memoryStream = ms; AMFReader amfReader = new AMFReader(_memoryStream); AMFWriter amfWriter = new AMFWriter(_memoryStream); _dataOutput = new DataOutput(amfWriter); _dataInput = new DataInput(amfReader); } }
// Public Methods (2) //from: http://trac.opensubtitles.org/projects/opensubtitles/wiki/XMLRPC //for gzip compression use function which adds no header to output, //for PHP it is: base64_encode(gzencode($subfilecontents)) public static byte[] CompressZlib(byte[] rawBuffer) { using (var compressedOutput = new MemoryStream()) { using (var rawStream = new MemoryStream(rawBuffer)) { using (var compressedStream = new ZlibStream(compressedOutput, Ionic.Zlib.CompressionMode.Compress, CompressionLevel.Default, false)) { var buffer = new byte[4096]; int byteCount; do { byteCount = rawStream.Read(buffer, 0, buffer.Length); if (byteCount > 0) { compressedStream.Write(buffer, 0, byteCount); } } while (byteCount > 0); } } return(compressedOutput.ToArray()); } }
public void SetChunkData(byte[] cData, Boolean isCompressed = true) { MemoryStream byteStream = new MemoryStream(); ZlibStream zStream = new ZlibStream(byteStream, CompressionMode.Decompress, CompressionLevel.BestCompression, true); zStream.Write(cData, 0, cData.Length); zStream.Flush(); zStream.Dispose(); zStream = null; byte[] bytes = byteStream.ToArray(); byteStream.Dispose(); byteStream = null; Block b; WorldLocation blockLoc; int x, y, z; // Block Types for (int i = 0; i < 32768; i++) { x = (Location.X * 16) + (i >> 11); y = i & 0x7F; z = (Location.Z * 16) + ((i & 0x780) >> 7); blockLoc = new WorldLocation(x, y, z); b = new Block((BlockType)bytes[i], blockLoc); Blocks.Add(b); } // TODO: Read and handle block/sky light and metadata bytes = null; }
public CompressedData(IEnumerable <MatrixElement> elements) { _elements = elements; // Get uncompressed data byte[] uncompressed; using (var memoryStream = new MemoryStream()) { using (var binaryWriter = new BinaryWriter(memoryStream)) { foreach (var element in _elements) { element.WriteToStream(binaryWriter); } binaryWriter.Flush(); memoryStream.Flush(); uncompressed = memoryStream.ToArray(); } } // Get compressed data using (var memoryStream = new MemoryStream()) { using (var compressor = new ZlibStream(memoryStream, CompressionMode.Compress, CompressionLevel.BestCompression)) { compressor.Write(uncompressed, 0, uncompressed.Length); } _bytes = memoryStream.ToArray(); } }
/// <summary> /// 지정된 데이타를 압축한다. /// </summary> /// <param name="input">압축할 Data</param> /// <returns>압축된 Data</returns> public override byte[] Compress(byte[] input) { if (IsDebugEnabled) { log.Debug(CompressorTool.SR.CompressStartMsg); } // check input data if (input.IsZeroLength()) { if (IsDebugEnabled) { log.Debug(CompressorTool.SR.InvalidInputDataMsg); } return(CompressorTool.EmptyBytes); } byte[] output; using (var outStream = new MemoryStream(input.Length)) { using (var zlib = new ZlibStream(outStream, CompressionMode.Compress)) { zlib.Write(input, 0, input.Length); } output = outStream.ToArray(); } if (IsDebugEnabled) { log.Debug(CompressorTool.SR.CompressResultMsg, input.Length, output.Length, output.Length / (double)input.Length); } return(output); }
public static byte[] WriteZLIBFile(CompoundTag tag, NBTEndian endian = NBTEndian.LITTLE_ENDIAN) { using (NBTStream stream = new NBTStream(endian)) { tag.Write(stream); int sum = 0; using (MemoryStream ms = new MemoryStream()) { ms.WriteByte(0x78); ms.WriteByte(0x01); using (ZlibStream zlib = new ZlibStream(ms, CompressionMode.Compress, true)) { zlib.Write(stream.ToArray(), 0, (int)stream.Length); sum = zlib.Checksum; } byte[] sumBytes = BitConverter.GetBytes(sum); if (BitConverter.IsLittleEndian) { Array.Reverse(sumBytes); } ms.Write(sumBytes, 0, sumBytes.Length); return(ms.ToArray()); } } }
private void NextBlock() { MemoryStream compressed = new MemoryStream(); using (ZlibStream compStream = new ZlibStream(compressed, CompressionMode.Compress, true)) { compStream.Write(_currentBlock, 0, _currentOffset); } byte[] writeData; ushort writeLen; if (compressed.Length < _currentOffset) { writeData = compressed.GetBuffer(); writeLen = (ushort)compressed.Length; } else { writeData = _currentBlock; writeLen = (ushort)(_currentOffset | 0x8000); } byte[] header = new byte[2]; Utilities.WriteBytesLittleEndian(writeLen, header, 0); _buffer.Write(header, 0, 2); _buffer.Write(writeData, 0, writeLen & 0x7FFF); ++_currentBlockNum; }
/// <summary> /// Writes a block of file data, possibly compressing it. /// </summary> /// <param name="buffer">The data to write</param> /// <param name="offset">Offset of the first byte to write</param> /// <param name="count">The number of bytes to write</param> /// <returns> /// The 'length' of the (possibly compressed) data written, including /// a flag indicating compression (or not). /// </returns> private uint WriteDataBlock(byte[] buffer, int offset, int count) { MemoryStream compressed = new MemoryStream(); using (ZlibStream compStream = new ZlibStream(compressed, CompressionMode.Compress, true)) { compStream.Write(buffer, offset, count); } byte[] writeData; int writeOffset; int writeLen; if (compressed.Length < count) { writeData = compressed.GetBuffer(); writeOffset = 0; writeLen = (int)compressed.Length; } else { writeData = buffer; writeOffset = offset; writeLen = count | 0x01000000; } _context.RawStream.Write(writeData, writeOffset, writeLen & 0xFFFFFF); return (uint)writeLen; }