本文整理汇总了C#中DeflateStream.Read方法的典型用法代码示例。如果您正苦于以下问题:C# DeflateStream.Read方法的具体用法?C# DeflateStream.Read怎么用?C# DeflateStream.Read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DeflateStream
的用法示例。
在下文中一共展示了DeflateStream.Read方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Decompress
public static byte[] Decompress(byte[] data)
{
try
{
string result = string.Empty;
byte[] buffer = { };
MemoryStream ms = new MemoryStream(data);
Stream s = new DeflateStream(ms, CompressionMode.Decompress);
int len = 4096;
while (true)
{
int oldLen = buffer.Length;
Array.Resize(ref buffer, oldLen + len);
int size = s.Read(buffer, oldLen, len);
if (size != len)
{
Array.Resize(ref buffer, buffer.Length - (len - size));
break;
}
if (size <= 0)
break;
}
s.Close();
return buffer;
}
catch
{
return null;
}
}
示例2: Inflate
public static byte[] Inflate(this byte[] data)
{
using (MemoryStream input = new MemoryStream(data))
{
input.Write(data, 0, data.Length);
input.Position = 0;
using (DeflateStream gzip = new DeflateStream(input, CompressionMode.Decompress))
{
using (MemoryStream output = new MemoryStream())
{
var buffer = new byte[ushort.MaxValue]; int count;
while ((count = gzip.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, count);
}
return output.ToArray();
}
}
}
}
示例3: WrapStreamReturningBadReadValues
public async Task WrapStreamReturningBadReadValues()
{
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress))
Assert.Throws<InvalidDataException>(() => ds.Read(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress))
await Assert.ThrowsAsync<InvalidDataException>(() => ds.ReadAsync(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress))
Assert.Equal(0, ds.Read(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress))
Assert.Equal(0, await ds.ReadAsync(new byte[1024], 0, 1024));
}
示例4: SequentialReadsOnMemoryStream_Return_SameBytes
public void SequentialReadsOnMemoryStream_Return_SameBytes()
{
byte[] data = new byte[1024 * 10];
new Random(42).NextBytes(data);
var compressed = new MemoryStream();
using (var compressor = new DeflateStream(compressed, CompressionMode.Compress, true))
{
for (int i = 0; i < data.Length; i += 1024)
{
compressor.Write(data, i, 1024);
}
}
compressed.Position = 0;
using (var decompressor = new DeflateStream(compressed, CompressionMode.Decompress, true))
{
int i, j;
byte[] array = new byte[100];
byte[] array2 = new byte[100];
// only read in the first 100 bytes
decompressor.Read(array, 0, array.Length);
for (i = 0; i < array.Length; i++)
Assert.Equal(data[i], array[i]);
// read in the next 100 bytes and make sure nothing is missing
decompressor.Read(array2, 0, array2.Length);
for (j = 0; j < array2.Length; j++)
Assert.Equal(data[j], array[j]);
}
}
示例5: ReadWriteArgumentValidation
public void ReadWriteArgumentValidation()
{
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<ArgumentNullException>(() => ds.Write(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Write(new byte[1], 0, -1));
Assert.Throws<ArgumentException>(() => ds.Write(new byte[1], 0, 2));
Assert.Throws<ArgumentException>(() => ds.Write(new byte[1], 1, 1));
Assert.Throws<InvalidOperationException>(() => ds.Read(new byte[1], 0, 1));
ds.Write(new byte[1], 0, 0);
}
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Compress))
{
Assert.Throws<ArgumentNullException>(() => { ds.WriteAsync(null, 0, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], -1, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.WriteAsync(new byte[1], 0, -1); });
Assert.Throws<ArgumentException>(() => { ds.WriteAsync(new byte[1], 0, 2); });
Assert.Throws<ArgumentException>(() => { ds.WriteAsync(new byte[1], 1, 1); });
Assert.Throws<InvalidOperationException>(() => { ds.Read(new byte[1], 0, 1); });
}
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress))
{
Assert.Throws<ArgumentNullException>(() => ds.Read(null, 0, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ds.Read(new byte[1], 0, -1));
Assert.Throws<ArgumentException>(() => ds.Read(new byte[1], 0, 2));
Assert.Throws<ArgumentException>(() => ds.Read(new byte[1], 1, 1));
Assert.Throws<InvalidOperationException>(() => ds.Write(new byte[1], 0, 1));
var data = new byte[1] { 42 };
Assert.Equal(0, ds.Read(data, 0, 0));
Assert.Equal(42, data[0]);
}
using (var ds = new DeflateStream(new MemoryStream(), CompressionMode.Decompress))
{
Assert.Throws<ArgumentNullException>(() => { ds.ReadAsync(null, 0, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], -1, 0); });
Assert.Throws<ArgumentOutOfRangeException>(() => { ds.ReadAsync(new byte[1], 0, -1); });
Assert.Throws<ArgumentException>(() => { ds.ReadAsync(new byte[1], 0, 2); });
Assert.Throws<ArgumentException>(() => { ds.ReadAsync(new byte[1], 1, 1); });
Assert.Throws<InvalidOperationException>(() => { ds.Write(new byte[1], 0, 1); });
}
}
示例6: TestCtor
private static void TestCtor(CompressionLevel level, bool? leaveOpen = null)
{
//Create the DeflateStream
int _bufferSize = 1024;
var bytes = new byte[_bufferSize];
var baseStream = new MemoryStream(bytes, true);
DeflateStream ds;
if (leaveOpen == null)
{
ds = new DeflateStream(baseStream, level);
}
else
{
ds = new DeflateStream(baseStream, level, leaveOpen ?? false);
}
//Write some data and Close the stream
string strData = "Test Data";
var encoding = Encoding.UTF8;
byte[] data = encoding.GetBytes(strData);
ds.Write(data, 0, data.Length);
ds.Flush();
ds.Dispose();
if (leaveOpen != true)
{
//Check that Close has really closed the underlying stream
Assert.Throws<ObjectDisposedException>(() => { baseStream.Write(bytes, 0, bytes.Length); });
}
//Read the data
byte[] data2 = new byte[_bufferSize];
baseStream = new MemoryStream(bytes, false);
ds = new DeflateStream(baseStream, CompressionMode.Decompress);
int size = ds.Read(data2, 0, _bufferSize - 5);
//Verify the data roundtripped
for (int i = 0; i < size + 5; i++)
{
if (i < data.Length)
{
Assert.Equal(data[i], data2[i]);
}
else
{
Assert.Equal(data2[i], (byte)0);
}
}
}
示例7: DecompressFailsWithRealGzStream
public async Task DecompressFailsWithRealGzStream()
{
string[] files = { gzTestFile("GZTestDocument.doc.gz"), gzTestFile("GZTestDocument.txt.gz") };
foreach (string fileName in files)
{
var baseStream = await LocalMemoryStream.readAppFileAsync(fileName);
var zip = new DeflateStream(baseStream, CompressionMode.Decompress);
int _bufferSize = 2048;
var bytes = new byte[_bufferSize];
Assert.Throws<InvalidDataException>(() => { zip.Read(bytes, 0, _bufferSize); });
zip.Dispose();
}
}
示例8: Decompress
public async void Decompress(CompressionType type)
{
string testFilePath = CreateCompressedFile(type);
int _bufferSize = 1024;
int retCount = -1;
var bytes = new byte[_bufferSize];
using (MemoryStream gzStream = await LocalMemoryStream.readAppFileAsync(testFilePath))
using (MemoryStream strippedMs = StripHeaderAndFooter.Strip(gzStream))
foreach (var iteration in Benchmark.Iterations)
using (iteration.StartMeasurement())
for (int i = 0; i < 20000; i++)
{
using (DeflateStream zip = new DeflateStream(strippedMs, CompressionMode.Decompress, leaveOpen: true))
{
while (retCount != 0)
{
retCount = zip.Read(bytes, 0, _bufferSize);
}
}
strippedMs.Seek(0, SeekOrigin.Begin);
}
File.Delete(testFilePath);
}
示例9: FromXML
public override void FromXML(XmlNode node)
{
if (node != null && node.Name == "layer")
{
XmlAttributeCollection attrs = node.Attributes;
m_name = attrs["name"].Value;
m_layerDimensions.first = Convert.ToInt32(attrs["width"].Value);
m_layerDimensions.second = Convert.ToInt32(attrs["height"].Value);
foreach(XmlNode child in node.ChildNodes)
{
if (child.Name == "properties")
{
foreach (XmlNode propertyNode in child)
{
if (propertyNode.Name != "property")
continue;
XmlAttributeCollection propertyAtts = propertyNode.Attributes;
m_properties[propertyAtts["name"].Value] = propertyAtts["value"].Value;
}
}
else if (child.Name == "data")
{
m_data = new TileData();
attrs = child.Attributes;
if (attrs["encoding"]!= null)
{
string[] encodings = { "", "csv", "base64" };
string encodingValue = attrs["encoding"].Value;
int encodingIdx = Array.IndexOf(encodings, encodingValue);
if (encodingIdx >= 0)
{
m_data.m_encoding = (TileEncodingType)encodingIdx;
}
string[] compressions = { "", "gzip", "zlib" };
string compression = attrs["compression"].Value;
int compressionIdx = Array.IndexOf(compressions, compression);
if (compressionIdx >= 0)
{
m_data.m_compression = (TileCompressionType)compressionIdx;
}
switch(m_data.m_encoding)
{
case TileEncodingType.kCSV:
{
string text = child.InnerText;
string[] values = text.Split(',');
foreach (string v in values)
{
uint value = Convert.ToUInt32(v);
TileInfo info = new TileInfo();
info.m_horizontalFlip = (value & FLIPPED_HORIZONTALLY_FLAG) != 0;
info.m_verticalFlip = (value & FLIPPED_VERTICALLY_FLAG) != 0;
info.m_diagonalFlip = (value & FLIPPED_DIAGONALLY_FLAG) != 0;
value = value & ~(FLIPPED_DIAGONALLY_FLAG | FLIPPED_HORIZONTALLY_FLAG | FLIPPED_VERTICALLY_FLAG);
info.m_gid = value;
m_data.m_tiles.Add(info);
}
break;
}
case TileEncodingType.kBase64:
{
byte[] bytes = null;
switch(m_data.m_compression)
{
case TileCompressionType.kNone:
{
bytes = Convert.FromBase64String(child.InnerText);
break;
}
case TileCompressionType.kGzip:
{
//Transform string into byte[]
string str = child.InnerText;
byte[] byteArray = new byte[str.Length];
int indexBA = 0;
foreach (char item in str.ToCharArray())
{
byteArray[indexBA++] = (byte)item;
}
MemoryStream ms = new MemoryStream(byteArray);
GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);
byteArray = new byte[byteArray.Length];
int rBytes = gzip.Read(byteArray, 0, byteArray.Length);
StringBuilder sb = new StringBuilder(rBytes);
for (int i = 0; i < rBytes; ++i)
{
sb.Append((char)byteArray[i]);
}
gzip.Close();
ms.Close();
gzip.Dispose();
ms.Dispose();
bytes = Convert.FromBase64String(sb.ToString());
//.........这里部分代码省略.........
示例10: Deflate
/// <summary>
/// Deflates the specified bytes.
/// </summary>
/// <param name="bytes">The bytes.</param>
/// <returns>The deflated bytes.</returns>
private static byte[] Deflate(byte[] bytes)
{
//// http://en.wikipedia.org/wiki/DEFLATE
//// http://www.nuget.org/packages/Microsoft.Bcl.Compression/
#if NET
var inputStream = new MemoryStream(bytes);
var deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress);
var buffer = new byte[4096];
var outputStream = new MemoryStream();
while (true)
{
var l = deflateStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, l);
if (l < buffer.Length)
{
break;
}
}
return outputStream.ToArray();
#elif BCL_COMPRESSION
// TODO: use Microsoft.Bcl.Compression
#else
return OxyPlot.Deflate.Decompress(bytes);
#endif
}
示例11: ProcessChunk
/// <exception cref="PngProcessingException"/>
/// <exception cref="System.IO.IOException"/>
private static IEnumerable<Directory> ProcessChunk([NotNull] PngChunk chunk)
{
// For more guidance:
// http://www.w3.org/TR/PNG-Decoders.html#D.Text-chunk-processing
// http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html#C.iCCP
// by spec, PNG is generally supposed to use this encoding
const string defaultEncodingName = "ISO-8859-1";
var defaultEncoding = Encoding.GetEncoding(defaultEncodingName);
var chunkType = chunk.ChunkType;
var bytes = chunk.Bytes;
if (chunkType == PngChunkType.IHDR)
{
var header = new PngHeader(bytes);
var directory = new PngDirectory(PngChunkType.IHDR);
directory.Set(PngDirectory.TagImageWidth, header.ImageWidth);
directory.Set(PngDirectory.TagImageHeight, header.ImageHeight);
directory.Set(PngDirectory.TagBitsPerSample, header.BitsPerSample);
directory.Set(PngDirectory.TagColorType, header.ColorType.NumericValue);
directory.Set(PngDirectory.TagCompressionType, header.CompressionType);
directory.Set(PngDirectory.TagFilterMethod, header.FilterMethod);
directory.Set(PngDirectory.TagInterlaceMethod, header.InterlaceMethod);
yield return directory;
}
else if (chunkType == PngChunkType.PLTE)
{
var directory = new PngDirectory(PngChunkType.PLTE);
directory.Set(PngDirectory.TagPaletteSize, bytes.Length / 3);
yield return directory;
}
else if (chunkType == PngChunkType.tRNS)
{
var directory = new PngDirectory(PngChunkType.tRNS);
directory.Set(PngDirectory.TagPaletteHasTransparency, 1);
yield return directory;
}
else if (chunkType == PngChunkType.sRGB)
{
int srgbRenderingIntent = unchecked((sbyte)bytes[0]);
var directory = new PngDirectory(PngChunkType.sRGB);
directory.Set(PngDirectory.TagSrgbRenderingIntent, srgbRenderingIntent);
yield return directory;
}
else if (chunkType == PngChunkType.cHRM)
{
var chromaticities = new PngChromaticities(bytes);
var directory = new PngChromaticitiesDirectory();
directory.Set(PngChromaticitiesDirectory.TagWhitePointX, chromaticities.WhitePointX);
directory.Set(PngChromaticitiesDirectory.TagWhitePointY, chromaticities.WhitePointY);
directory.Set(PngChromaticitiesDirectory.TagRedX, chromaticities.RedX);
directory.Set(PngChromaticitiesDirectory.TagRedY, chromaticities.RedY);
directory.Set(PngChromaticitiesDirectory.TagGreenX, chromaticities.GreenX);
directory.Set(PngChromaticitiesDirectory.TagGreenY, chromaticities.GreenY);
directory.Set(PngChromaticitiesDirectory.TagBlueX, chromaticities.BlueX);
directory.Set(PngChromaticitiesDirectory.TagBlueY, chromaticities.BlueY);
yield return directory;
}
else if (chunkType == PngChunkType.gAMA)
{
var gammaInt = ByteConvert.ToInt32BigEndian(bytes);
var directory = new PngDirectory(PngChunkType.gAMA);
directory.Set(PngDirectory.TagGamma, gammaInt / 100000.0);
yield return directory;
}
else if (chunkType == PngChunkType.iCCP)
{
var reader = new SequentialByteArrayReader(bytes);
var profileName = reader.GetNullTerminatedStringValue(maxLengthBytes: 79);
var directory = new PngDirectory(PngChunkType.iCCP);
directory.Set(PngDirectory.TagIccProfileName, profileName);
var compressionMethod = reader.GetSByte();
if (compressionMethod == 0)
{
// Only compression method allowed by the spec is zero: deflate
// This assumes 1-byte-per-char, which it is by spec.
var bytesLeft = bytes.Length - profileName.Bytes.Length - 2;
var compressedProfile = reader.GetBytes(bytesLeft);
using (var inflaterStream = new InflaterInputStream(new MemoryStream(compressedProfile)))
{
var iccDirectory = new IccReader().Extract(new IndexedCapturingReader(inflaterStream));
iccDirectory.Parent = directory;
yield return iccDirectory;
}
}
else
{
directory.AddError("Invalid compression method value");
}
yield return directory;
}
else if (chunkType == PngChunkType.bKGD)
{
var directory = new PngDirectory(PngChunkType.bKGD);
directory.Set(PngDirectory.TagBackgroundColor, bytes);
yield return directory;
}
else if (chunkType == PngChunkType.tEXt)
//.........这里部分代码省略.........
示例12: ReadPacket
void ReadPacket( byte opcode )
{
reader.Remove( 1 ); // remove opcode
lastOpcode = (PacketId)opcode;
switch( (PacketId)opcode ) {
case PacketId.Handshake:
{
byte protocolVer = reader.ReadUInt8();
ServerName = reader.ReadAsciiString();
ServerMotd = reader.ReadAsciiString();
game.LocalPlayer.SetUserType( reader.ReadUInt8() );
receivedFirstPosition = false;
game.LocalPlayer.ParseHackFlags( ServerName, ServerMotd );
} break;
case PacketId.Ping:
break;
case PacketId.LevelInitialise:
{
game.Map.Reset();
game.SetNewScreen( new LoadingMapScreen( game, ServerName, ServerMotd ) );
if( ServerMotd.Contains( "cfg=" ) ) {
ReadWomConfigurationAsync();
}
receivedFirstPosition = false;
gzipHeader = new GZipHeaderReader();
// Workaround because built in mono stream assumes that the end of stream
// has been reached the first time a read call returns 0. (MS.NET doesn't)
#if __MonoCS__
gzipStream = new DeflateStream( gzippedMap, true );
#else
gzipStream = new DeflateStream( gzippedMap, CompressionMode.Decompress );
if( OpenTK.Configuration.RunningOnMono ) {
Utils.LogWarning( "You are running on Mono, but this build does not support the Mono workaround." );
Utils.LogWarning( "You should either download the Mono compatible build or define '__MonoCS__' when targeting Mono. " +
"(The Mono compiler already defines this by default)" );
Utils.LogWarning( "You will likely experience an 'Internal error (no progress possible) ReadInternal' exception when decompressing the map." );
}
#endif
mapSizeIndex = 0;
mapIndex = 0;
receiveStart = DateTime.UtcNow;
} break;
case PacketId.LevelDataChunk:
{
int usedLength = reader.ReadInt16();
gzippedMap.Position = 0;
gzippedMap.SetLength( usedLength );
if( gzipHeader.done || gzipHeader.ReadHeader( gzippedMap ) ) {
if( mapSizeIndex < 4 ) {
mapSizeIndex += gzipStream.Read( mapSize, mapSizeIndex, 4 - mapSizeIndex );
}
if( mapSizeIndex == 4 ) {
if( map == null ) {
int size = mapSize[0] << 24 | mapSize[1] << 16 | mapSize[2] << 8 | mapSize[3];
map = new byte[size];
}
mapIndex += gzipStream.Read( map, mapIndex, map.Length - mapIndex );
}
}
reader.Remove( 1024 );
byte progress = reader.ReadUInt8();
game.Events.RaiseMapLoading( progress );
} break;
case PacketId.LevelFinalise:
{
game.SetNewScreen( new NormalScreen( game ) );
int mapWidth = reader.ReadInt16();
int mapHeight = reader.ReadInt16();
int mapLength = reader.ReadInt16();
double loadingMs = ( DateTime.UtcNow - receiveStart ).TotalMilliseconds;
Utils.LogDebug( "map loading took:" + loadingMs );
game.Map.UseRawMap( map, mapWidth, mapHeight, mapLength );
game.Events.RaiseOnNewMapLoaded();
map = null;
gzipStream.Close();
if( sendWomId && !sentWomId ) {
SendChat( "/womid WoMClient-2.0.7" );
sentWomId = true;
}
gzipStream = null;
GC.Collect( 0 );
} break;
case PacketId.SetBlock:
{
int x = reader.ReadInt16();
int y = reader.ReadInt16();
int z = reader.ReadInt16();
byte type = reader.ReadUInt8();
if( !game.Map.IsNotLoaded )
game.UpdateBlock( x, y, z, type );
else
//.........这里部分代码省略.........
示例13: GetHttpResponse
string GetHttpResponse(HttpWebResponse res)
{
const int WorkingBufferSize = 1024;
string requestTokenResponse = string.Empty;
string contentEncoding = string.Empty;
using (var respStream = res.GetResponseStream())
{
#if !SILVERLIGHT || WINDOWS_PHONE
contentEncoding = res.Headers["Content-Encoding"] ?? "";
#endif
if (contentEncoding.ToLower().Contains("gzip"))
{
using (var gzip = new GZipStream(respStream, CompressionMode.Decompress))
{
using (var memStr = new MemoryStream())
{
byte[] buffer = new byte[WorkingBufferSize];
int n;
while ((n = gzip.Read(buffer, 0, buffer.Length)) != 0)
{
memStr.Write(buffer, 0, n);
}
memStr.Position = 0;
using (var strmRdr = new StreamReader(memStr))
{
requestTokenResponse = strmRdr.ReadToEnd();
}
}
}
}
else if (contentEncoding.ToLower().Contains("deflate"))
{
using (var gzip = new DeflateStream(respStream, CompressionMode.Decompress))
{
using (var memStr = new MemoryStream())
{
byte[] buffer = new byte[WorkingBufferSize];
int n;
while ((n = gzip.Read(buffer, 0, buffer.Length)) != 0)
{
memStr.Write(buffer, 0, n);
}
memStr.Position = 0;
using (var strmRdr = new StreamReader(memStr))
{
requestTokenResponse = strmRdr.ReadToEnd();
}
}
}
}
else
{
using (var respReader = new StreamReader(respStream))
{
requestTokenResponse = respReader.ReadToEnd();
}
}
}
return requestTokenResponse;
}
示例14: DecompressDisplay
/// <summary>
/// Decompress and display the update contents
/// </summary>
/// <param name="data">data bytes</param>
private void DecompressDisplay(byte[] data)
{
var compressedStream = new MemoryStream(data);
Int32 x, y, w, h;
using (MemoryStream clearStream = new MemoryStream()) {
using (DeflateStream zipStream = new DeflateStream(compressedStream, CompressionMode.Decompress)) {
byte[] buffer = new byte[4096];
byte[] szBuf = new byte[4];
int readAmt;
readAmt = zipStream.Read(szBuf, 0, 4);
Debug.Assert(readAmt == 4);
UInt32 hdr = System.BitConverter.ToUInt32(szBuf, 0);
hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
width = (Int32)(hdr >> 16);
height = (Int32)(hdr & 0xFFFF);
readAmt = zipStream.Read(szBuf, 0, 4);
Debug.Assert(readAmt == 4);
hdr = System.BitConverter.ToUInt32(szBuf, 0);
hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
maskX = (Int32)(hdr >> 16);
maskY = (Int32)(hdr & 0xFFFF);
readAmt = zipStream.Read(szBuf, 0, 4);
Debug.Assert(readAmt == 4);
hdr = System.BitConverter.ToUInt32(szBuf, 0);
hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
maskWidth = (Int32)(hdr >> 16);
maskHeight = (Int32)(hdr & 0xFFFF);
if (!((prevMX == maskX) && (prevMY == maskY) && (prevMW == maskWidth) && (prevMH == maskHeight))) {
DisplayMask(maskX, maskY, maskWidth, maskHeight, width, height);
prevMX = maskX;
prevMY = maskY;
prevMW = maskWidth;
prevMH = maskHeight;
}
readAmt = zipStream.Read(szBuf, 0, 4);
Debug.Assert(readAmt == 4);
hdr = System.BitConverter.ToUInt32(szBuf, 0);
hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
x = (Int32)(hdr >> 16);
y = (Int32)(hdr & 0xFFFF);
readAmt = zipStream.Read(szBuf, 0, 4);
Debug.Assert(readAmt == 4);
hdr = System.BitConverter.ToUInt32(szBuf, 0);
hdr = (UInt32)System.Net.IPAddress.NetworkToHostOrder((Int32)hdr);
w = (Int32)(hdr >> 16);
h = (Int32)(hdr & 0xFFFF);
int read = 0;
while (true) {
try {
read = zipStream.Read(buffer, 0, buffer.Length);
} catch (Exception e) {
// Trace.WriteLine("{0} Error code: {}.", e.Message, e.ErrorCode);
MessageBox.Show("Message: " + e.Message, "FATAL");
}
if (read > 0)
clearStream.Write(buffer, 0, read);
else
break;
}
zipStream.Close();
}
DisplayUpdate(x, y, w, h, clearStream.ToArray());
}
}
示例15: Zlib_ParallelDeflateStream
public void Zlib_ParallelDeflateStream()
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
TestContext.WriteLine("{0}: Zlib_ParallelDeflateStream Start", sw.Elapsed);
int sz = 256*1024 + this.rnd.Next(120000);
string FileToCompress = System.IO.Path.Combine(TopLevelDir, String.Format("Zlib_ParallelDeflateStream.{0}.txt", sz));
CreateAndFillFileText( FileToCompress, sz);
TestContext.WriteLine("{0}: Created file: {1}", sw.Elapsed, FileToCompress );
byte[] original = File.ReadAllBytes(FileToCompress);
int crc1 = DoCrc(FileToCompress);
TestContext.WriteLine("{0}: Original CRC: {1:X8}", sw.Elapsed, crc1 );
byte[] working = new byte[WORKING_BUFFER_SIZE];
int n = -1;
long originalLength;
MemoryStream ms1 = new MemoryStream();
{
using (FileStream fs1 = File.OpenRead(FileToCompress))
{
originalLength = fs1.Length;
using (var compressor = new Ionic.Zlib.ParallelDeflateOutputStream(ms1, true))
{
while ((n = fs1.Read(working, 0, working.Length)) != 0)
{
compressor.Write(working, 0, n);
}
}
}
ms1.Seek(0, SeekOrigin.Begin);
}
TestContext.WriteLine("{0}: Compressed {1} bytes into {2} bytes", sw.Elapsed,
originalLength, ms1.Length);
var crc = new Ionic.Crc.CRC32();
int crc2= 0;
byte[] decompressedBytes= null;
using (MemoryStream ms2 = new MemoryStream())
{
using (var decompressor = new DeflateStream(ms1, CompressionMode.Decompress, false))
{
while ((n = decompressor.Read(working, 0, working.Length)) != 0)
{
ms2.Write(working, 0, n);
}
}
TestContext.WriteLine("{0}: Decompressed", sw.Elapsed);
TestContext.WriteLine("{0}: Decompressed length: {1}", sw.Elapsed, ms2.Length);
ms2.Seek(0, SeekOrigin.Begin);
crc2 = crc.GetCrc32(ms2);
decompressedBytes = ms2.ToArray();
TestContext.WriteLine("{0}: Decompressed CRC: {1:X8}", sw.Elapsed, crc2 );
}
TestContext.WriteLine("{0}: Checking...", sw.Elapsed );
bool check = true;
if (originalLength != decompressedBytes.Length)
{
TestContext.WriteLine("Different lengths.");
check = false;
}
else
{
for (int i = 0; i < decompressedBytes.Length; i++)
{
if (original[i] != decompressedBytes[i])
{
TestContext.WriteLine("byte {0} differs", i);
check = false;
break;
}
}
}
Assert.IsTrue(check,"Data check failed");
TestContext.WriteLine("{0}: Done...", sw.Elapsed );
}