public static void Create(string oFile, string cFile, string outFile) { if (outFile.Length == 0) { outFile = Path.GetDirectoryName(cFile) + "\\" + Path.GetFileNameWithoutExtension(cFile) + ".ips"; } //TODO: Make sure the files are not over the limit (16MB) byte[] oB = File.ReadAllBytes(oFile); byte[] cB = File.ReadAllBytes(cFile); byte[] tIPS = new byte[FILE_LIMIT]; Array.Copy(PATCH_ASCII, 0, tIPS, 0, PATCH_ASCII.Length); //the offset of the ips file int iOffset = PATCH_ASCII.Length-1; //I suppose we assume that the changed file must be the same size or larger for (int c = 0; c < cB.Length; c++) { if (c >= oB.Length || !(oB[c].Equals(cB[c]))) { byte[] record = new byte[RECORD_LIMIT]; int o = 0; RLE rle = new RLE(); for (o = 0; o < RECORD_LIMIT; o++) { int p = (c + o); if ((c == EOF_INTEGER) && o == 0) {//A workaround because this position looks like EOF in ASCII c--; p = (c + o); record[o] = cB[p]; } else if (o < 5 || c >= oB.Length || !(oB[p].Equals(cB[p])) || ((o > 4) && Differences(oB, cB, p, 16))) { record[o] = cB[p]; } else { break; } } //check for RLE encode-able data rle = RLECheck(record, o); //then write the record if (o > 0) { if ((rle.max) > 8) { if (rle.start > 0) {//then write IPS and RLE record int oriO = o; o = rle.start - 1; WriteIPS(tIPS, record, o, ref c, ref iOffset); WriteRLE(tIPS, record, rle, ref c, ref iOffset); //in case rle doesnt go to the end of the record... o = oriO - (rle.start + rle.max) + 1; if (o > 0) { WriteIPS(tIPS, record, o, ref c, ref iOffset); } } else {//only write RLE WriteRLE(tIPS, record, rle, ref c, ref iOffset); } } else { WriteIPS(tIPS, record, o, ref c, ref iOffset); } } } } //Now write the EOF and finalize Array.Copy(EOF_ASCII, 0, tIPS, iOffset += 1, EOF_ASCII.Length); iOffset += EOF_ASCII.Length; byte[] final = new byte[iOffset]; Array.Copy(tIPS, final, iOffset); File.WriteAllBytes(outFile, final); }
static void WriteRLE(byte[] tIPS, byte[] record, RLE rle, ref int c, ref int iOffset) { //Write IPS Offset tIPS[iOffset += 1] = (byte)((c >> 16) & 0xFF); tIPS[iOffset += 1] = (byte)((c >> 8) & 0xFF); tIPS[iOffset += 1] = (byte)(c & 0xFF); //Write IPS Size of Record tIPS[iOffset += 1] = 0; tIPS[iOffset += 1] = 0; //Write RLE Size of Record tIPS[iOffset += 1] = (byte)((rle.max >> 8) & 0xFF); tIPS[iOffset += 1] = (byte)(rle.max & 0xFF); //Write Record... tIPS[iOffset += 1] = (byte)record[rle.start]; c += rle.max; //return iOffset; }
public void CompressDecompress() { Random r = new Random(0); const int n = 1600; RLEData[] rledata = new RLEData[n]; for (int i = 0; i < n; i++) { rledata[i] = new RLEData((short)r.Next(0, 100)); } RLE <RLEData> rle = new RLE <RLEData>(); rle.Compress(ref rledata); RLEData[] decompressed = rle.Decompress(); for (int i = 0; i < n; i++) { Assert.AreEqual(rledata[i], decompressed[i]); } }
public static void Main(String[] args) { String encodedFileName = "Encoded.txt"; String fileToEncode = "handmade1.txt"; //String str = "AAAAABBCCCD"; string[] lines = File.ReadAllLines(fileToEncode); var wholeText = ""; foreach (string line in lines) { wholeText += line; } var encoded = RLE.encode(wholeText); //Console.WriteLine(encoded); using StreamWriter outputFile = new StreamWriter("Encoded.txt"); outputFile.Write(encoded); Console.WriteLine("Compression Ratio: " + CompressionRatio.Calculate(wholeText, encoded).ToString()); Console.WriteLine("Source BitRate: " + BitRate.Calculate(wholeText).ToString()); Console.WriteLine("Coded BitRate: " + BitRate.Calculate(wholeText, encoded).ToString()); Console.WriteLine("Saving Percentage: " + SavingPercentage.Calculate (wholeText, encoded).ToString() + "%"); Console.WriteLine("Saving Percentage (File): " + SavingPercentage.CalculateFile( Path.Combine(Environment.CurrentDirectory, fileToEncode), Path.Combine(Environment.CurrentDirectory, encodedFileName)).ToString() + "%"); Console.WriteLine("Compression Ratio (File): " + CompressionRatio.CalculateFile(Path. Combine(Environment.CurrentDirectory, fileToEncode), Path.Combine(Environment.CurrentDirectory, encodedFileName)).ToString()); }
public static FormatCompress Get_Format(string input) { CompressionFormat fmt = null; foreach (FormatCompress f in Enum.GetValues(typeof(FormatCompress))) { switch (f) { //case FormatCompress.LZOVL: fmt = new LZOvl(); break; case FormatCompress.LZ10: fmt = new LZ10(); break; case FormatCompress.LZ11: fmt = new LZ11(); break; case FormatCompress.RLE: fmt = new RLE(); break; case FormatCompress.HUFF: fmt = new Huffman(); break; } if (fmt == null) { continue; } if (fmt.Supports(input)) { return(f); } } return(FormatCompress.Invalid); }
public static Tileset Load(string fname) { FileStream f = new FileStream(fname, FileMode.Open); BinaryReader stream = new BinaryReader(f); Tileset t = new Tileset(); UInt16 version = stream.ReadUInt16(); if (version != 3) { throw new Exception(String.Format("v2Tileset: {0} is not a valid VERGE VSP", fname)); } byte[] pal = new byte[768]; stream.Read(pal, 0, 768); // palette UInt16 numtiles = stream.ReadUInt16(); int bufsize = stream.ReadInt32(); byte[] buffer = new byte[bufsize]; stream.Read(buffer, 0, bufsize); byte[] pixeldata = new byte[numtiles * 16 * 16]; RLE.Read(pixeldata, numtiles * 16 * 16, buffer); CreateTileImages(t, numtiles, pixeldata, pal); stream.Close(); f.Close(); return(t); }
public bool RunLengthEncodingProperty(IEnumerable <Tuple <int, char> > r) { var original = r.ToList(); var actual = RLE.RunLengthEnc(RLE.RunLengthDec(original)); return(actual.SequenceEqual(original)); }
public void GetDelta(T document) { byte[] documentByteArr; if (document != null) { BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { bf.Serialize(ms, document); documentByteArr = ms.ToArray(); } int[] delta = null; for (int i = 0; i <= this.refrence.Length; i++) { delta[i] = this.refrence[i] - documentByteArr[i]; } var result = RLE<int>.Encode(delta.ToList<int>())); return string.Concat(result); } }
public static byte[] Decompress(Stream stream) { using (var reader = new ImprovedBinaryReader(stream, true)) { var header = reader.ReadInt32(); var method = (Method)(header & 0x07); var size = header >> 3; switch (method) { case Method.NoCompression: return(reader.ReadBytes(size)); case Method.LZ10: return(LZ10.Decompress(reader.BaseStream, size)); case Method.RLE: return(RLE.Decompress(reader.BaseStream, size)); case Method.Huffman4Bit: return(Huffman.Decompress(reader.BaseStream, 4, size)); case Method.Huffman8Bit: return(Huffman.Decompress(reader.BaseStream, 8, size)); default: throw new NotImplementedException($"Unsupported compression method: {method}"); } } }
public void Serialize(IOWriter writer) { // Don't save the terrain layer, there is no point. // Save Z layers, using run length encoding (TODO) // Compresses using run length encoding (obviously has to be lossless). // Compressed in vertical strips due to data structure indexing. Tile[] toSave = new Tile[tiles.Length - SIZE * SIZE]; Array.Copy(tiles, SIZE * SIZE, toSave, 0, toSave.Length); var compressed = RLE.Compress <Tile>(toSave, (current, next) => { return(current.ID == next.ID && current.ColorRef == next.ColorRef && next.EntityID == 0); }, out int squased); Debug.Log($"Squshed {squased} of {tiles.Length} tiles, that's {((float)squased / (tiles.Length - SIZE * SIZE))*100f:F1}%. Segments: {compressed.Count}."); // Write total segment count. writer.Write((ushort)compressed.Count); // Write compressed data. foreach (var pair in compressed) { writer.Write((ushort)pair.count); writer.Write(pair.data.ID); writer.Write(pair.data.ColorRef); writer.Write(pair.data.EntityID); } }
static void Main(string[] args) { RLE r = new RLE(); string output = r.Decipher(r.Cipher("Eestaaa eesss uuuna pruueba")); Console.WriteLine(output); Console.ReadKey(); }
private void BuildBackgrounds() { SignalManager.Get <WriteBuildOutputSignal>().Dispatch("Building background", OutputMessageType.Information); ProjectModel projectModel = ModelManager.Get <ProjectModel>(); List <FileModelVO> models = ProjectFiles.GetModels <MapModel>(); foreach (FileModelVO item in models) { MapModel model = item.Model as MapModel; string fullPath = Path.Combine(Path.GetFullPath(projectModel.Build.OutputFilePath), item.Name + ".s"); using (StreamWriter outputFile = new StreamWriter(fullPath)) { outputFile.WriteLine("; This file is autogenerated!"); outputFile.Write(Environment.NewLine); outputFile.WriteLine($"nt_{item.Name}:"); List <byte> serializedMap = new List <byte>(); SerializeNametable(model, ref serializedMap); if (projectModel.Build.UseRLEOnMaps) { RLE.Compress(serializedMap, out List <byte> compressedData); serializedMap = compressedData; } FormatBytes(serializedMap, outputFile, 32); serializedMap.Clear(); if (model.ExportAttributeTable) { outputFile.WriteLine($"att_{item.Name}:"); SerializeAttributes(model, ref serializedMap); if (projectModel.Build.UseRLEOnMaps) { RLE.Compress(serializedMap, out List <byte> compressedData); serializedMap = compressedData; } FormatBytes(serializedMap, outputFile, 8); } PrintMetaData(model, item, outputFile); } } SignalManager.Get <WriteBuildOutputSignal>().Dispatch("Finishing building background", OutputMessageType.Information); }
public static void Main(string[] args) { RLE r = new RLE(); string output = r.Cipher("Estaa ees uuuna prueba"); Console.WriteLine(output); Console.ReadKey(); }
private byte[] DecodePicture(ref int index, uint length) { byte bits = _bytes[index++]; byte[] img = new byte[length - 5]; Array.Copy(_bytes, index, img, 0, (int)(length - 5)); index += (int)(length - 5); return(RLE.Decode(LZW.Decode(img))); }
public Stream DecodeStream(Stream s) { RLE rle = new RLE(); MemoryStream outStream = new MemoryStream(); rle.Decompress(s, s.Length, outStream); outStream.Position = 0; return(outStream); }
static void Main(string[] args) { RLE r = new RLE(); string output = (r.CaesarCipher("Eestaaa eesss uuuna pruueba", "password")); Console.WriteLine(output); Console.ReadKey(); //Console.WriteLine(((char)250).ToString()); }
public Property RunLengthEncodingPropertyFluent(IEnumerable <Tuple <int, char> > rParam) { return(Spec .For(Any.Value(rParam), r => { var original = r.ToList(); var actual = RLE.RunLengthEnc(RLE.RunLengthDec(original)); return actual.SequenceEqual(original); }) .Build()); }
private static void Export(string inputPath, string outputPath) { var inputBytes = File.ReadAllBytes(inputPath); if (BitConverter.ToUInt32(inputBytes, 0) == 0x67687361) // 'ashg' { inputBytes = RLE.Decompress(inputBytes, 0, inputBytes.Length); } var file = new SpriteFile(); using (var input = new MemoryStream(inputBytes, false)) { file.Deserialize(input, Endian.Little); } var sprite = file.Sprite; if (sprite.Texture != null) { var texture = sprite.Texture.Value; if (sprite.Palettes.Length == 1) { var bitmapPath = Path.ChangeExtension(outputPath, ".png"); var data = ExportPalettized(texture, sprite.Palettes[0]); var bitmap = MakeBitmapPalettized( texture.TotalWidth, texture.TotalHeight, data, sprite.Palettes[0]); using (bitmap) { bitmap.Save(bitmapPath, ImageFormat.Png); } } else { int i = 0; foreach (var palette in sprite.Palettes) { var bitmapPath = Path.ChangeExtension($"{outputPath}_{i}", ".png"); var data = ExportPalettized(texture, palette); var bitmap = MakeBitmapPalettized( texture.TotalWidth, texture.TotalHeight, data, palette); using (bitmap) { bitmap.Save(bitmapPath, ImageFormat.Png); } i++; } } } }
static void Main(string[] args) { byte[] packBytes = File.ReadAllBytes("../../files/TEST.txt"); File.WriteAllBytes("../../files/TEST Pack.txt", RLE.Pack(packBytes)); byte[] unpackBytes = File.ReadAllBytes("../../files/TEST Pack.txt"); File.WriteAllBytes("../../files/TEST Unpack.txt", RLE.Unpack(unpackBytes)); Console.WriteLine("Done!"); Console.Read(); }
public void RunLengthEncodingTestFluent() { Spec .For(GenOutput, r => { var original = r.ToList(); var actual = RLE.RunLengthEnc(RLE.RunLengthDec(original)); return(actual.SequenceEqual(original)); }) .Check(Configuration); }
public void RunLengthEncodingTest() { var arb = Arb.fromGen(GenOutput); var body = FSharpFunc <IEnumerable <Tuple <int, char> >, bool> .FromConverter(r => { var original = r.ToList(); var actual = RLE.RunLengthEnc(RLE.RunLengthDec(original)); return(actual.SequenceEqual(original)); }); Check.One(Config, Prop.forAll(arb, body)); }
public void Pack_Sample() { byte[] packData = Encoding.UTF8.GetBytes("SSSSSJJJJJDDDUUWBBSSSSSSS>>>>>>>>"); byte[] expectedData = Encoding.UTF8.GetBytes("5S 5J 3D 2U 1W 2B 7S 8> "); byte[] actualData = RLE.Pack(packData); for (int i = 0; i < actualData.Length; i++) { Assert.AreEqual(expectedData[i], actualData[i]); } }
public void Unpack_Sample() { byte[] unpackData = Encoding.UTF8.GetBytes("12W 1B 12W 3B 24W 1B 14W "); byte[] expectedData = Encoding.UTF8.GetBytes("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"); byte[] actualData = RLE.Unpack(unpackData); for (int i = 0; i < actualData.Length; i++) { Assert.AreEqual(expectedData[i], actualData[i]); } }
// Зашифровать private void perform1_Click(object sender, EventArgs e) { List <string> result = new List <string>(); try { string chiper = comboBox1.SelectedItem.ToString(); if (textBox1.Text.Length > 0) { switch (chiper) { case "Перестановки": result.Add(func.permutationСipher(textBox1.Text)); break; case "RSA": result = method_Rsa.Value.EncryptionRsa(textBox1.Text, textBox_x.Text, textBox_y.Text); textBox_d.Text = result[1]; textBox_n.Text = result[2]; break; case "Диффи-Хеллмана": result = method_DH.Value.diffieHellman(textBox1.Text, textBox_x.Text, textBox_y.Text, textBox_q.Text, textBox_v.Text); textBox_k.Text = result[1]; break; case "TEA": result = method_Tea.Value.EncryptString(textBox1.Text, textBox_TEA_key.Text); textBox_TEA_key2.Text = result[1]; break; case "Бит четности": result = method_ParityCheck.Value.Encoding(textBox1.Text); break; case "RLE": result = RLE.Encode(textBox1.Text); break; } textBox_result_chiper.Text = result[0]; } else { MessageBox.Show("Введите текст"); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
// Расшифровать private void button3_Click(object sender, EventArgs e) { textBox_result_decryption.Clear(); string result = String.Empty; string chiper = comboBox2.SelectedItem.ToString(); if (chiper.Length != 0) { if (textBox2.Text.Length > 0) { switch (chiper) { case "Перестановка": result = func.permutationСipher(textBox2.Text); break; case "RSA": result = method_Rsa.Value.DecryptionRsa(textBox2.Text, textBox_d.Text, textBox_n.Text); break; case "Диффи-Хеллмана": result = method_DH.Value.diffieHellman_Decode(textBox2.Text, textBox_k.Text); break; case "TEA": result = method_Tea.Value.Decrypt(textBox2.Text, textBox_TEA_key2.Text); break; case "Бит четности": result = method_ParityCheck.Value.Decoding(textBox2.Text); break; case "RLE": result = RLE.Decode(textBox2.Text); break; } textBox_result_decryption.Text = result; } else { label_message2.Text = "Пустая строка"; } } else { MessageBox.Show("Выберите метод!"); } }
public static int DoCompress(string infile, MemoryStream output, FormatCompress format, out FormatCompress actualFormat) { CompressionFormat fmt = null; switch (format) { case FormatCompress.LZ10: fmt = new LZ10(); break; case FormatCompress.LZ11: fmt = new LZ11(); break; case FormatCompress.LZOVL: fmt = new LZOvl(); break; case FormatCompress.RLE: fmt = new RLE(); break; case FormatCompress.HUFF4: Huffman.CompressBlockSize = Huffman.BlockSize.FOURBIT; fmt = new Huffman(); break; case FormatCompress.HUFF8: Huffman.CompressBlockSize = Huffman.BlockSize.EIGHTBIT; fmt = new Huffman(); break; case FormatCompress.HUFF: return(CompressHuff(infile, output, out actualFormat)); case FormatCompress.GBA: return(CompressGBA(infile, output, out actualFormat)); case FormatCompress.NDS: return(CompressNDS(infile, output, out actualFormat)); default: actualFormat = FormatCompress.Invalid; return(-1); } actualFormat = format; using (FileStream inStream = File.OpenRead(infile)) { try { return(fmt.Compress(inStream, inStream.Length, output)); } catch (Exception s) { // any exception generated by compression is a fatal exception Console.WriteLine(s.Message); return(-1); } } }
private static int DoCompress(string infile, MemoryStream output, Formats format, out Formats actualFormat) { CompressionFormat fmt = null; switch (format) { case Formats.LZ10: fmt = new LZ10(); break; case Formats.LZ11: fmt = new LZ11(); break; case Formats.LZOVL: fmt = new LZOvl(); break; case Formats.RLE: fmt = new RLE(); break; case Formats.HUFF4: fmt = new Huffman4(); break; case Formats.HUFF8: fmt = new Huffman8(); break; case Formats.HUFF: return(CompressHuff(infile, output, out actualFormat)); case Formats.GBA: return(CompressGBA(infile, output, out actualFormat)); case Formats.NDS: return(CompressNDS(infile, output, out actualFormat)); default: throw new Exception("Unhandled compression format " + format); } actualFormat = format; using (FileStream inStream = File.OpenRead(infile)) { try { return(fmt.Compress(inStream, inStream.Length, output)); } catch (Exception s) { // any exception generated by compression is a fatal exception Console.WriteLine(s.Message); return(-1); } } }
public bool DrawPalImage(int imageIndex) { if (ImagesPal == null || ImagesPal.Count <= imageIndex) { return(false); } if (imageIndex < 0 || imageIndex >= ImagesPal.Count) { return(false); } RoSpriteImagePal sprImg = ImagesPal[imageIndex]; if (Version >= 0x201 && sprImg.Decoded == false) { sprImg.Data = RLE.Decode(sprImg.Data); sprImg.Decoded = true; } if (sprImg.Data == null || sprImg.Data.Length == 0 || sprImg.Width < 1 || sprImg.Height < 1) { return(false); } sprImg.Image = new Bitmap(sprImg.Width, sprImg.Height); FastBitmap fb = new FastBitmap(sprImg.Image); int index; fb.LockImage(); for (int x = 0; x < sprImg.Width; x++) { for (int y = 0; y < sprImg.Height; y++) { index = (x + (y * sprImg.Width)); if (index >= sprImg.Data.Length) { fb.SetPixel(x, y, Color.Transparent); continue; } fb.SetPixel(x, y, Palette[sprImg.Data[index]]); } } fb.UnlockImage(); return(true); }
public void Unpack_Over255chars() { byte[] unpackData = Encoding.UTF8.GetBytes("1540A "); string data = ""; for (int i = 0; i < 1540; i++) { data += "A"; } byte[] expectedData = Encoding.UTF8.GetBytes(data); byte[] actualData = RLE.Unpack(unpackData); for (int i = 0; i < actualData.Length; i++) { Assert.AreEqual(expectedData[i], actualData[i]); } }
private static long Decompress(MemoryStream inputStream, MemoryStream output, FormatCompress format) { CompressionFormat realFormat = null; switch (format) { case FormatCompress.HUFF: realFormat = new Huffman(); break; case FormatCompress.LZ10: realFormat = new LZ10(); break; case FormatCompress.LZ11: realFormat = new LZ11(); break; case FormatCompress.LZOVL: realFormat = new LZOvl(); break; case FormatCompress.RLE: realFormat = new RLE(); break; default: return(-1); } if (!realFormat.Supports(inputStream, inputStream.Length)) { return(-1); } try { return(realFormat.Decompress(inputStream, inputStream.Length, output)); } catch (TooMuchInputException e) { Console.WriteLine(e.Message); return(output.Length); } catch (Exception e) { Console.WriteLine(String.Format(Main.Get_Traduction("S1D"), format.ToString(), e.Message)); return(-1); } }
static void Test(byte[] bytes, Method method) { var bytes2 = new byte[bytes.Length]; switch (method) { case Method.RLE: bytes2 = RLE.Decompress(new MemoryStream(RLE.Compress(new MemoryStream(bytes))), bytes.Length); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.Yaz0: bytes2 = Yaz0.Decompress(new MemoryStream(Yaz0.Compress(new MemoryStream(bytes)))); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; case Method.Yay0: bytes2 = Yay0.Decompress(new MemoryStream(Yay0.Compress(new MemoryStream(bytes)))); Assert.IsTrue(bytes.SequenceEqual(bytes2)); break; } }
static RLE RLECheck(byte[] record, int o) { RLE rle = new RLE(); int count = 0; int start = 0; rle.start = 0; rle.max = 0; byte rcheck = record[0]; for (int c = 1; c < o; c++) { if (rcheck.Equals(record[c])) { if (count == 0) start = c; count++; if (count > rle.max) { rle.start = start; rle.max = count; } } else { count = 0; rcheck = record[c]; } } if (rle.max > 0) rle.max++; //because we need this not to be a zero-based number return rle; }