public void Deflate() { string hello = "hello world"; byte[] bytes = Zlib.DeflateString(hello); string base64 = Base64.Encode(bytes); }
public static byte[] UncompressChunk(ref byte[] iBytes, int outSize) { Console.WriteLine(Environment.CurrentDirectory); // zlib doesn't seem to work in 64bit, try this, and fallback to trying zlib if failed //if (is64BitProcess && File.Exists(ExternalCompressionName)) //{ // var hex = HeroDesigner.ZLib.Helpers.byteArrayToHexString(iBytes); // var proc = Process.Start(new ProcessStartInfo(ExternalCompressionName, "uncompress " + iBytes.Length + " " + outSize + " \"" + hex + "\"") // { // UseShellExecute = false, // RedirectStandardOutput = true, // }); // var output = proc.StandardOutput.ReadToEnd(); // if (proc.ExitCode == 0) // { // var text = new string(output.SkipWhile(x => x != '-').SkipWhile(x => x == '-').TakeWhile(x => x != '-').ToArray()).Trim(); // var bytes = HeroDesigner.ZLib.Helpers.hexStringToByteArray(text); // return bytes; // } //} int length = iBytes.Length; int destLength = outSize; byte[] array = new byte[destLength]; if (Zlib.Uncompress(ref array[0], ref destLength, ref iBytes[0], length) == 0) { Array.Resize(ref array, destLength); return(array); } else { return(Array.Empty <byte>()); } }
private static void ExtractHg3ImageJpegAlpha(BinaryReader reader, Hg3FrameInfo frameInfo, HgxOptions options, string pngFile) { HG3STDINFO std = frameInfo.StdInfo; HG3IMG_AL img = frameInfo.ImgAl.Data; HG3TAG tag = frameInfo.ImgJpg.Tag; reader.BaseStream.Position = frameInfo.ImgAl.Offset; // WGC handles bad alpha buffer errors gracefully, so we should too byte[] alphaBuffer; try { alphaBuffer = Zlib.Decompress(reader, img.CompressedLength, img.DecompressedLength); } catch (ZlibException ex) { if (ex.Result == ZResult.DataError || ex.Result == ZResult.BufferError) { alphaBuffer = ex.OutputBuffer; } else { throw; } } reader.BaseStream.Position = frameInfo.ImgJpg.Offset; byte[] buffer = reader.ReadBytes(tag.Length); if (!CatDebug.SpeedTestHgx) { WriteJpegAlphaMaskToPng(buffer, alphaBuffer, std, options, pngFile); } }
private void CopyResponse(Image <Rgba32> bitmap) { bitmap.Mutate((s) => s.Resize(new ResizeOptions() { Mode = ResizeMode.Max, Size = new Size(384, 384) })); using var stream2 = new MemoryStream(); bitmap.Save(stream2, new JpegEncoder()); byte[] tmp = stream2.ToArray(); stream2.SetLength(0); Zlib.Compress(stream2, tmp); tmp = new byte[4000]; Reset(); stream2.Position = 0; while (true) { int count = stream2.Read(tmp, 0, tmp.Length); if (count == 0) { break; } Write(tmp, 0, count); } Size = (uint)Received; Chunks = ChunkCount; }
public static void WritePacked(this Span <byte> dest, ref int pos, ReadOnlySpan <byte> source) { var length = source.Length; if (length == 0) { #if NO_LOCAL_INIT dest.Write(ref pos, 0); #else pos += 4; #endif return; } var packLength = (ulong)dest.Length - 8; ZlibError ce = Zlib.Pack(dest.Slice(pos + 8), ref packLength, source, ZlibQuality.Default); if (ce != ZlibError.Okay) { Console.WriteLine("ZLib error: {0} (#{1})", ce, (int)ce); } dest.Write(ref pos, (int)(4 + packLength)); dest.Write(ref pos, length); pos += (int)packLength; }
public void ExtractStream() { var fileName = @"C:\Users\sal\Desktop\Hey.pdf"; var offset = 550; var compressedSize = 1132; var file = File.OpenRead(fileName); file.Seek(offset, SeekOrigin.Begin); int b; while ((b = file.ReadByte()) != 'm') { ; } while ((b = file.ReadByte()) != '\n') { ; } var streamOffset = file.Position; var compressedBytes = new byte[compressedSize]; file.Read(compressedBytes); var bytes = Zlib.Inflate(compressedBytes); var s = Encoding.ASCII.GetString(bytes); }
object TryToParse(Type type, byte[] data) { try { var stream = new MemoryStream(data); var obj = ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(stream, null, type); if (stream.Position != stream.Length) { throw new Exception("Not enough data readed."); } return(obj); } catch (Exception ex) { Console.WriteLine("Try to decode this data: " + ex.Message); } byte code = data[data.Length - 1]; for (int i = 0; i < data.Length - 1; i++) { data[i] ^= code; } data = Zlib.DeCompress(data); return(ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(new MemoryStream(data), null, type)); }
public override void Action(BinaryWriter writer) { var uncompressedData = Zlib.Decompress(compressedData); if (GetCalculatedUncompressedDataSize() != uncompressedData.Length) { Debug.LogError("Uncompressed size != calculated size!"); } for (int i = 0; i < 16; ++i) { var chunk = ChunkManager.Get().GetChunk(new Vector3(x, i * 16, z)); if ((primaryBitMap & (1 << i)) != 0) { for (int ix = 0; ix < 16; ++ix) { for (int iy = 0; iy < 16; ++iy) { for (int iz = 0; iz < 16; ++iz) { chunk.SetBlock(ix, iy, iz, uncompressedData[GetUncompressedDataIndex(i, ix, iy, iz)]); } } } } chunk.Loaded = true; } ChunkManager.LoadedChunks++; }
private static void WritePacked(ref SpanWriter writer, ReadOnlySpan <byte> span) { var length = span.Length; if (length == 0) { writer.Write(0); return; } var wantLength = 1 + span.Length * 1024 / 1000; wantLength += 4095; wantLength &= ~4095; var packBuffer = ArrayPool <byte> .Shared.Rent(wantLength); var packLength = wantLength; Zlib.Pack(packBuffer, ref packLength, span, length, ZlibQuality.Default); writer.Write(4 + packLength); writer.Write(length); writer.Write(packBuffer.AsSpan(0, packLength)); ArrayPool <byte> .Shared.Return(packBuffer); }
public void SendPacket(IPacket packet) { PacketBuffer sendBuffer = new PacketBuffer(); packet.Send(sendBuffer); byte[] packetIdVI = ByteUtils.ToVarInt(packet.GetId()); byte[] packetData = ByteUtils.Concat(packetIdVI, sendBuffer.ToArray()); if (compressionThreshold > 0) { if (packetData.Length > compressionThreshold) { byte[] uncompressed_length = ByteUtils.ToVarInt(packetData.Length); byte[] compressed_packet = Zlib.Compress(packetData); byte[] compressed_packet_length = ByteUtils.ToVarInt(compressed_packet.Length); packetData = ByteUtils.Concat(compressed_packet_length, compressed_packet); } else { byte[] uncompressed_length = ByteUtils.ToVarInt(0); packetData = ByteUtils.Concat(uncompressed_length, packetData); } } byte[] lengthVI = ByteUtils.ToVarInt(packetData.Length); var l = ByteUtils.Concat(lengthVI, packetData); SendBytes(l); }
private void LoadCallback(IAsyncResult ar) { var lr = (LoadRequest)ar.AsyncState; Bitmap bmp1 = null; Bitmap bmp2 = null; WebResponse response = null; try { response = lr.Request.EndGetResponse(ar); using (var stream = response.GetResponseStream()) { bmp1 = (Bitmap)Bitmap.FromStream(stream); bmp2 = ScaleImage(bmp1, 384, 384); using (var stream2 = new MemoryStream()) { bmp2.Save(stream2, ImageFormat.Jpeg); byte[] tmp = stream2.ToArray(); stream2.SetLength(0); Zlib.Compress(stream2, tmp); tmp = new byte[4000]; Reset(); stream2.Position = 0; while (true) { int count = stream2.Read(tmp, 0, tmp.Length); if (count == 0) { break; } Write(tmp, 0, count); } Size = (uint)Received; Chunks = ChunkCount; } } lr.Callback(lr.State); } catch (Exception ex) { lr.Callback(ex); } finally { if (bmp1 != null) { bmp1.Dispose(); } if (bmp2 != null) { bmp2.Dispose(); } } }
public void SendPacket(int id, PacketBuffer buffer) { byte[] packetIdVI = ByteUtils.ToVarInt(id); byte[] packetData = ByteUtils.Concat(packetIdVI, buffer.ReadToEnd()); if (compressionThreshold > 0) { if (packetData.Length > compressionThreshold) { byte[] uncompressed_length = ByteUtils.ToVarInt(packetData.Length); byte[] compressed_packet = Zlib.Compress(packetData); byte[] compressed_packet_length = ByteUtils.ToVarInt(compressed_packet.Length); packetData = ByteUtils.Concat(compressed_packet_length, compressed_packet); } else { byte[] uncompressed_length = ByteUtils.ToVarInt(0); packetData = ByteUtils.Concat(uncompressed_length, packetData); } } byte[] lengthVI = ByteUtils.ToVarInt(packetData.Length); var l = ByteUtils.Concat(lengthVI, packetData); SendBytes(l); }
public static string SendRequest(string url, string body) { // send request Log.Info(Constants.backendUrl + url); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Constants.backendUrl + url); byte[] data = Zlib.Compress(Encoding.UTF8.GetBytes(body)); request.Method = "POST"; request.ContentType = "text/plain"; request.AutomaticDecompression = DecompressionMethods.Deflate; request.ContentLength = data.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } // get response Stream responseData = request.GetResponse().GetResponseStream(); using (MemoryStream ms = new MemoryStream()) { responseData.CopyTo(ms); return(Encoding.UTF8.GetString(Zlib.Decompress(ms.ToArray()))); } }
public void AddFilesV3(List <string> files, string srcdir, string dstdir) { Stream.Reopen(false); SetProgressMax?.Invoke(files.Count); int cl = Settings.CompressionLevel; Stream.Seek(-280, SeekOrigin.End); long current_end = Stream.ReadInt64() ^ Key.KEY_1; foreach (string file in files) { SetProgressNext?.Invoke(); byte[] data = File.ReadAllBytes(file); int size = data.Length; byte[] compressed = Zlib.Compress(data, cl); if (compressed.Length < size) { data = compressed; } string path = (dstdir + file.RemoveFirst(srcdir).RemoveFirstSeparator()).RemoveFirstSeparator(); var entry = Files.Where(x => x.Path == path).ToList(); if (entry.Count > 0) { if (data.Length <= entry[0].CSize) { entry[0].Size = size; entry[0].CSize = data.Length; Stream.Seek(entry[0].Offset, SeekOrigin.Begin); Stream.WriteBytes(data); } else { entry[0].Size = size; entry[0].CSize = data.Length; entry[0].Offset = current_end; Stream.Seek(current_end, SeekOrigin.Begin); current_end += data.Length; Stream.WriteBytes(data); } } else { Files.Add(new ArchiveEntryV3() { Path = path, Size = size, CSize = data.Length, Offset = current_end }); Stream.Seek(current_end, SeekOrigin.Begin); current_end += data.Length; Stream.WriteBytes(data); } } SaveFileTable(current_end); SetProgress?.Invoke(0); LoadData?.Invoke(0); LoadData?.Invoke(1); }
private static XmlElement ProcessCompressed(IProcessXmlSoapClient client, TwinfieldProcessXmlService.Header header, XmlDocument input) { byte[] compressedInput = Zlib.CompressXml(input); byte[] compressedOutput = client.ProcessXmlCompressed(header, compressedInput); XmlDocument document = Zlib.DecompressXml(compressedOutput); return(document == null ? null : document.DocumentElement); }
internal void SendRoomScribble(Predicate <IClient> pred, string name, RoomScribble scribble) { byte[] buffer; if (scribble.Size <= 4000) { Server.SendAnnounce(pred, string.Format("\x000314--- From {0}", name)); Server.SendPacket(pred, new ClientCustom(string.Empty, "cb0t_scribble_once", scribble.RawImage())); } else { scribble.Index = 0; int length = Math.Min((int)scribble.Received, 4000); buffer = scribble.Read(); Server.SendAnnounce(pred, string.Format("\x000314--- From {0}", name)); Server.SendPacket(pred, new ClientCustom(string.Empty, "cb0t_scribble_first", buffer)); while (scribble.Remaining > 0) { buffer = scribble.Read(); if (scribble.Remaining > 0) { Server.SendPacket(pred, new ClientCustom(string.Empty, "cb0t_scribble_chunk", buffer)); } else { Server.SendPacket(pred, new ClientCustom(string.Empty, "cb0t_scribble_last", buffer)); } } } var ib0ts = Server.Users.Where(s => s.Socket.Isib0tSocket && pred(s)); if (ib0ts.Count() > 0) { buffer = Zlib.Decompress(scribble.RawImage()); int height = RoomScribble.GetHeight(buffer); string base64 = Convert.ToBase64String(buffer); string[] chunks = new string[(int)Math.Round((double)(base64.Length / 1024), MidpointRounding.AwayFromZero)]; for (int i = 0; i < chunks.Length; i++) { chunks[i] = base64.Substring(i * 1024, 1024); } ib0ts.ForEach(s => s.SendPacket(new ScribbleHead(name, height, chunks.Length))); foreach (string chunk in chunks) { ib0ts.ForEach(s => s.SendPacket(new ScribbleBlock(chunk))); } } }
// Used for protobuf json strings. public static byte[] Deflate <T>(string name, T data) { var jsonData = Encoding.UTF8.GetBytes(name + ":" + CreateString(data) + "\0"); var jsonDataLength = BitConverter.GetBytes(jsonData.Length); var zlibHeader = new byte[] { 0x78, 0x9C }; var compressedData = Zlib.Deflate(jsonData); var uncompressedAdler = BitConverter.GetBytes(Adler32.Calculate(jsonData)).Reverse().ToArray(); return(jsonDataLength.Concat(zlibHeader).Concat(compressedData).Concat(uncompressedAdler).ToArray()); }
public static byte[] Decompress(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException(); } using (MemoryStream buffStream = new MemoryStream(buffer)) { uint magicStream = buffStream.ReadValueU32(); if (magicStream != magic && magicStream.Swap() != magic) { throw new InvalidDataException("found an invalid zlib block"); } uint buffMaxSegmentSize = buffStream.ReadValueU32(); if (buffMaxSegmentSize != maxSegmentSize) { throw new FormatException(); } uint totComprSize = buffStream.ReadValueU32(); uint totUncomprSize = buffStream.ReadValueU32(); byte[] outputBuffer = new byte[totUncomprSize]; int numOfSegm = (int)Math.Ceiling(totUncomprSize / (double)maxSegmentSize); int headSegm = 16; int dataSegm = headSegm + (numOfSegm * 8); int buffOff = 0; for (int i = 0; i < numOfSegm; i++) { buffStream.Seek(headSegm, SeekOrigin.Begin); int comprSegm = buffStream.ReadValueS32(); int uncomprSegm = buffStream.ReadValueS32(); headSegm = (int)buffStream.Position; buffStream.Seek(dataSegm, SeekOrigin.Begin); //Console.WriteLine("compr size: {0}, uncompr size: {1}, data offset: 0x{2:X8}", comprSegm, uncomprSegm, dataSegm); byte[] src = buffStream.ReadBytes(comprSegm); byte[] dst = new byte[uncomprSegm]; if (Zlib.Decompress(src, (uint)src.Length, dst) != uncomprSegm) { throw new Exception("Zlib decompression failed!"); } Buffer.BlockCopy(dst, 0, outputBuffer, buffOff, uncomprSegm); buffOff += uncomprSegm; dataSegm += comprSegm; } buffStream.Close(); return(outputBuffer); } }
public void DeflateRencode() { var list = "hello_world"; string encode = Rencode.Encode(list); byte[] encodedBytes = encode.Select(Convert.ToByte).ToArray(); byte[] bytes = Zlib.Deflate(encodedBytes); string base64 = Base64.Encode(bytes); }
bool UncompressFile(string iRoot, BinaryReader reader) { Zlib.FileHeader fileHeader = default(Zlib.FileHeader); string str = reader.ReadString(); fileHeader.FileName = FileIO.StripSlash(iRoot) + str; fileHeader.DecompressedSize = reader.ReadInt32(); fileHeader.CompressedSize = reader.ReadInt32(); this._sFrm.StatusText2 = str; if (!Directory.Exists(fileHeader.FileName.Substring(0, fileHeader.FileName.LastIndexOf("\\", StringComparison.Ordinal)))) { Directory.CreateDirectory(fileHeader.FileName.Substring(0, fileHeader.FileName.LastIndexOf("\\", StringComparison.Ordinal))); } if (File.Exists(fileHeader.FileName)) { File.Delete(fileHeader.FileName); } FileStream fileStream; BinaryWriter binaryWriter; bool flag; try { fileStream = new FileStream(fileHeader.FileName, FileMode.Create); binaryWriter = new BinaryWriter(fileStream); } catch (Exception ex) { MessageBox.Show("An error occurred while opening files for writing for decompression: " + ex.Message, "Buh?"); flag = false; return(flag); } try { byte[] iBytes = reader.ReadBytes(fileHeader.CompressedSize); byte[] buffer = Zlib.UncompressChunk(ref iBytes, fileHeader.DecompressedSize); if (buffer.Length != fileHeader.DecompressedSize) { throw new Exception("Uncompressed data was not the expected size!"); } binaryWriter.Write(buffer); binaryWriter.Close(); fileStream.Close(); flag = true; } catch (Exception ex2) { MessageBox.Show("An error occurred during decompression: " + ex2.Message, "Buh?"); reader.Close(); fileStream.Close(); flag = false; } return(flag); }
public override ITexture ConvertToBitmap(Sprite entity) { var data = entity.Data; var type = entity.Type; var size = entity.Width * entity.Height * (type == ColorBits.ARGB_8888 ? 4 : 2); if (entity.CompressMode == CompressMode.ZLIB) { data = Zlib.Decompress(data, size); } return(TextureUitls.Instance.FromArray(data, entity.Size, type)); }
public override Bitmap ConvertToBitmap(Sprite entity) { var data = entity.Data; var type = entity.Type; var size = entity.Width * entity.Height * (type == ColorBits.ARGB_8888 ? 4 : 2); if (entity.Compress == Compress.ZLIB) { data = Zlib.Decompress(data, size); } return(Bitmaps.FromArray(data, entity.Size, type)); }
private static void ExtractHg3ImageAlpha(BinaryReader reader, Hg3FrameInfo frameInfo, HgxOptions options, string pngFile) { HG3STDINFO std = frameInfo.StdInfo; HG3IMG_AL img = frameInfo.ImgAl.Data; reader.BaseStream.Position = frameInfo.ImgAl.Offset; // WGC handles bad alpha buffer errors gracefully, so we should too byte[] alphaBuffer; try { alphaBuffer = Zlib.Decompress(reader, img.CompressedLength, img.DecompressedLength); } catch (ZlibException ex) { if (ex.Result == ZResult.DataError || ex.Result == ZResult.BufferError) { alphaBuffer = ex.OutputBuffer; } else { throw; } } int depthBytes = (std.DepthBits + 7) / 8; int stride = (std.Width * depthBytes + 3) & ~3; int minStride = (std.Width * depthBytes); int alphaStride = std.Width; byte[] pixelBuffer = new byte[stride * std.Height]; for (int y = 0; y < std.Height; y++) { int src = y * alphaStride; int dst = y * stride; for (int x = 0; x < std.Width; x++) { int alphaIndex = src + x; int pixelIndex = dst + x * depthBytes; byte alpha = unchecked ((byte)(byte.MaxValue - alphaBuffer[alphaIndex])); pixelBuffer[pixelIndex + 0] = alpha; pixelBuffer[pixelIndex + 1] = alpha; pixelBuffer[pixelIndex + 2] = alpha; if (depthBytes == 4) { pixelBuffer[pixelIndex + 3] = byte.MaxValue; } } } if (!CatDebug.SpeedTestHgx) { WritePng(pixelBuffer, std, options, pngFile); } }
public void Read(byte[] data) { if (data.Length < 276) { data = Zlib.Decompress(data, 276); } BinaryReader br = new BinaryReader(new MemoryStream(data)); Path = br.ReadBytes(260).ToGBK().Replace("/", "\\"); Offset = br.ReadUInt32(); Size = br.ReadInt32(); CSize = br.ReadInt32(); br.Close(); }
private byte[] SendJson(HttpListenerResponse response, string json) { if (response == null) { return(null); } Log.Data("SEND:" + Environment.NewLine + json); response.AddHeader("Content-Type", "text/plain"); response.AddHeader("Content-Encoding", "deflate"); byte[] buffer = Encoding.UTF8.GetBytes(json); return(Zlib.Compress(buffer)); }
protected void Page_Load(object sender, EventArgs e) { string guid = Request.QueryString[string.Empty]; if (guid == null || !Regex.IsMatch(guid, "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")) { Response.StatusCode = 301; Response.Status = "301 Moved Permanently"; Response.AddHeader("Location", SiteUri.ToString()); Response.End(); } Meta.SQL.IDatabase db = new Meta.SQL.Module().Database; Ps2Css.DB.Request.Module module = new Ps2Css.DB.Request.Module(db); Ps2Css.DB.Request.Item item = module.GetByID(new Guid(guid)); if (item != null) { int diff = (int)Math.Ceiling((DateTime.Now - item.Created).TotalSeconds); if (diff < InitialDelay) { this.wait = InitialDelay - diff; } else { this.wait = 0; try { Document doc = new Ps2Css.Xml.Document(Encoding.UTF8.GetString(Zlib.Decompress(item.Data))); this.Styles = doc.Styles.ToArray(); } catch (Ps2Css.Xml.CorruptedXmlException ex) { exception = ex.GetType().ToString(); base.Log("XML parsing error"); } catch (Exception ex) { exception = "System.Exception"; base.Log(ex); } } } else { if (Request.UrlReferrer != null) { exception = "StyleNotFound"; } } }
/* * Name function: Compress * Purpose: compress a part of the byte array into a Zlib Block * Input: - buffer: byte array * 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) { if (buffer == null) { throw new ArgumentNullException(); } MemoryStream headBlock = new MemoryStream(); MemoryStream dataBlock = new MemoryStream(); int numSeg = (int)Math.Ceiling(buffer.Length / (double)maxSegmentSize); headBlock.WriteValueU32(magic); headBlock.WriteValueU32(maxSegmentSize); headBlock.WriteValueU32(0x0); //total compressed size, still to calculate headBlock.WriteValueS32(buffer.Length); //total uncompressed size int offset = 0; for (int i = buffer.Length; i > 0; i -= (int)maxSegmentSize) { int copyBytes = Math.Min(i, (int)maxSegmentSize); uint precCompSize = (uint)dataBlock.Length; byte[] src = new byte[copyBytes]; Buffer.BlockCopy(buffer, offset, src, 0, copyBytes); byte[] dst = Zlib.Compress(src); if (dst.Length == 0) { throw new Exception("Zlib compression failed!"); } dataBlock.WriteBytes(dst); offset += dst.Length; headBlock.WriteValueU32((uint)dst.Length); //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 void DefragV3() { Stream.Reopen(true); long oldsize = Stream.GetLenght(); ArchiveManager am = new ArchiveManager(Path + ".defrag", Key, false) { Version = Version }; am.Stream.Reopen(false); am.Stream.WriteInt32(Key.FSIG_1); am.Stream.WriteInt64(0); am.Stream.WriteInt32(Key.FSIG_2); int cl = Settings.CompressionLevel; SetProgressMax?.Invoke(Files.Count); foreach (IArchiveEntry file in Files) { SetProgressNext?.Invoke(); byte[] data = GetFile(file, false); byte[] compressed = Zlib.Compress(data, cl); if (data.Length < compressed.Length) { compressed = data; } file.Offset = am.Stream.Position; file.Size = data.Length; file.CSize = compressed.Length; am.Stream.WriteBytes(compressed); } am.Files = Files; am.SaveFileTable(am.Stream.Position); am.Stream.Close(); Stream.Close(); File.Delete(Path); File.Move(Path + ".defrag", Path); string pkx = Path.Replace(".pck", ".pkx"); if (File.Exists(pkx)) { File.Delete(pkx); File.Move(pkx + ".defrag", pkx); } ReadFileTable(); Stream.Reopen(true); long newsize = Stream.GetLenght(); MessageBox.Show($"Old size: {oldsize}\nNew size: {newsize}"); }
static bool CompressFile(string iFileName, string iDest, BinaryWriter writer) { int int32 = Convert.ToInt32(new FileInfo(iFileName).Length); Zlib.FileHeader fileHeader = default(Zlib.FileHeader); fileHeader.FileName = iDest; fileHeader.DecompressedSize = int32; fileHeader.CompressedSize = 0; FileStream fileStream; BinaryReader binaryReader; bool flag; try { fileStream = new FileStream(iFileName, FileMode.Open); binaryReader = new BinaryReader(fileStream); } catch (Exception ex) { MessageBox.Show("An error occurred while compressing: " + ex.Message, "Buh?"); flag = false; return(flag); } try { byte[] iBytes = binaryReader.ReadBytes(int32); byte[] buffer = Zlib.CompressChunk(ref iBytes); fileHeader.CompressedSize = buffer.Length; if (fileHeader.CompressedSize < 1) { throw new Exception("Compressed data was 0 bytes long!"); } writer.Write(fileHeader.FileName); writer.Write(fileHeader.DecompressedSize); writer.Write(fileHeader.CompressedSize); writer.Write(buffer); binaryReader.Close(); fileStream.Close(); flag = true; } catch (Exception ex2) { MessageBox.Show("An error occurred during compression: " + ex2.Message, "Buh?"); binaryReader.Close(); fileStream.Close(); flag = false; } return(flag); }
public override async Task <RpcMessage[]> Receive() { CheckDisposed(); var buffer = new byte[BufferSize]; while (true) { int read = await stream.ReadAsync(buffer, 0, BufferSize); if (read == 0) { return(null); } IEnumerable <byte> bytesRead = buffer.Where((b, i) => i < read); readBuffer.AddRange(bytesRead); try { byte[] inflated = Zlib.Inflate(readBuffer.ToArray()); string encoded = string.Concat(inflated.Select(Convert.ToChar)); var result = Rencode.Decode(encoded) as object[]; if (result == null) { return(null); } var messages = new List <RpcMessage>(); const int partsPerMessage = 3; for (int skip = 0; skip < result.Length; skip += partsPerMessage) { object[] messageParts = result.Skip(skip).Take(partsPerMessage).ToArray(); RpcMessage message = RpcMessage.Create(messageParts); messages.Add(message); } readBuffer.Clear(); return(messages.ToArray()); } catch { // Message is incomplete } } }