Example #1
0
        public void DecompressFile(string path, string file_name)
        {
            LZW lzw = new LZW();

            byte[] buffer;


            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
            {
                buffer = new byte[fs.Length];
                using (var br = new BinaryReader(fs))
                {
                    br.Read(buffer, 0, buffer.Length);
                }
            }
            lzw = new LZW();
            byte[] result = lzw.DecodeData(buffer);

            string[] path_result = path.Split("Data");
            string   file_path   = path_result[0] + $"\\Data\\decompressions\\{file_name}";

            using (var fs = new FileStream(file_path, FileMode.OpenOrCreate))
            {
                fs.Write(result, 0, result.Length);
            }
        }
Example #2
0
        public static void TextLZWCompressor()
        {
            var compressed   = LZW.Compressor("TATAGATCTTAATATA");
            var decompressed = LZW.Decompressor(compressed);

            Console.WriteLine(decompressed);
        }
Example #3
0
        static void Main(string[] args)
        {
            string path        = @"C:\Users\joseg\Desktop\Pruebas LZW\Archivos\cuento.txt";
            string path2       = @"C:\Users\joseg\Desktop\Pruebas LZW\Descompresiones\cuento.txt";
            LZW    compression = new LZW(path);

            byte[] byte1;
            byte[] byte2;
            using (FileStream fs = File.OpenRead(path2))
            {
                using (FileStream fs2 = File.OpenRead(path))
                {
                    using (BinaryReader reader = new BinaryReader(fs))
                    {
                        using (BinaryReader reader2 = new BinaryReader(fs2))
                        {
                            int counter = 0;
                            while (counter < fs.Length)
                            {
                                byte1    = reader.ReadBytes(100);
                                byte2    = reader2.ReadBytes(100);
                                counter += 100;
                                Console.WriteLine(byte1.SequenceEqual(byte2));
                            }
                        }
                    }
                }
            }
            Console.WriteLine();
        }
Example #4
0
        public ActionResult Descargar(string path)
        {
            //Recuperar path
            path = path.Replace("~", "/");

            int cifradoValue = Int16.Parse(HttpContext.Request.Cookies["cifrado"].Value);

            //Descifrar
            SDES   cipher      = new SDES();
            string rutaCifrado = cipher.DescifrarArchivo(path, Directories.directorioTemporal, cifradoValue);

            //Descomprimir
            string rutaComprimido = LZW.descomprimirArchivo(rutaCifrado, Directories.directorioDescargas);

            //Descargar

            if (!String.IsNullOrEmpty(rutaComprimido))
            {
                byte[] filedata = System.IO.File.ReadAllBytes(rutaComprimido);

                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = Path.GetFileName(rutaComprimido),
                    Inline   = true,
                };

                Response.AppendHeader("Content-Disposition", cd.ToString());
                return(File(filedata, "application/force-download"));
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
Example #5
0
        public void Comprimir()
        {
            string directorio;

            directorio = root + @"\\Upload\\";
            if (!Directory.Exists(directorio + "\\Compresion\\"))
            {
                DirectoryInfo di = Directory.CreateDirectory(directorio + "\\Compresion\\");
            }
            List <int> comprimido = new List <int>();
            string     text       = System.IO.File.ReadAllText(@path);

            comprimido = LZW.Compresion(text);
            List <char> bytecompress = new List <char>();

            foreach (int numero in comprimido)
            {
                bytecompress.Add((char)numero);
            }
            NombreTemporal = NombreTemporal.Replace(".txt", "");
            root           = root + @"\\Upload\\Compresion\\" + NombreTemporal + "compresion" + ".lzw";

            using (StreamWriter outputFile = new StreamWriter(root))
            {
                foreach (char caracter in bytecompress)
                {
                    outputFile.Write(caracter.ToString());
                }
            }
        }
Example #6
0
File: Program.cs Project: rav97/LZW
    static void Main(string[] args)
    {
        string inputFilepath      = @"..\..\inputfile.txt";
        string outputFilepath     = @"..\..\compressed.bin";
        string outputDecompressed = @"..\..\decompressed.txt";

        string        inputText  = File.ReadAllText(inputFilepath, Encoding.ASCII);
        List <UInt16> compressed = LZW.LZW_Encode(inputText);

        byte[] bytes = ListToBytes(compressed);
        File.WriteAllBytes(outputFilepath, bytes);

        byte[]        readBytes = File.ReadAllBytes(outputFilepath);
        List <UInt16> readList  = BytesToList(readBytes);

        string decoded = LZW.LZW_Decode(readList);

        float l1 = (float)inputText.Length, l2 = (float)bytes.Length;

        Console.WriteLine("Plain text length: {0}", l1);
        Entropy(inputText);
        Console.WriteLine("Compressed text length: {0}", l2);
        Entropy(compressed);
        float compression = 100.0f * ((l1 - l2) / l1);

        Console.WriteLine("Compression rate: {0}", compression);

        File.WriteAllText(outputDecompressed, decoded);
    }
Example #7
0
        public void Post([FromForm(Name = "file")] IFormFile file, string name, string method)
        {
            string folder   = @"C:\Compressions\";
            string fullPath = folder + file.FileName;

            byte[] txt = new byte[file.Length];
            using (FileStream fs = new FileStream(fullPath, FileMode.Open))
            {
                int count;                            // actual number of bytes read
                int sum = 0;                          // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fs.Read(txt, sum, txt.Length - sum)) > 0)
                {
                    sum += count;  // sum is a buffer offset for next reading
                }
            }

            if (method.ToLower().Equals("huffman"))
            {
                Huffman huffmanMethods = new Huffman();
                huffmanMethods.DecodeFile(txt, name, file.FileName);
            }
            else if (method.ToLower().Equals("lzw"))
            {
                LZW lzwMethods = new LZW();
                lzwMethods.Decompress(txt, name);
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            Console.WriteLine("\t\t\t\t\t\t\t- LAB 4 -\n\nKevin Romero 1047519\nJosé De León 1072619");
            LZW lzw = new LZW();

            string original = "Tu trabajo va a llenar gran parte de tu vida, la única manera de estar realmente satisfecho es hacer lo que creas es un gran trabajo y la única manera de hacerlo es amar lo que haces. Si no lo has encontrado aún, sigue buscando. Como con todo lo que tiene que ver con el corazón, sabrás cuando lo hayas encontrado. -Steve Jobs";

            Console.WriteLine("\n\nTEXTO ORIGINAL          \n" + original);

            byte[] compression_result = lzw.EncodeData(ConvertToByte(original));
            Console.WriteLine("\n\nTEXTO COMPRIMIDO");
            Console.WriteLine(ConvertToChar(compression_result));

            double compression_factor   = lzw.CompressionFactor();
            double compression_ratio    = lzw.CompressionRatio();
            double reduction_percentage = lzw.ReductionPercentage();


            lzw = new LZW();
            byte[] descompression_result = lzw.DecodeData(compression_result);
            Console.WriteLine("\n\nTEXTO DESCOMPRIMIDO");
            Console.WriteLine(ConvertToChar(descompression_result));

            Console.WriteLine("\n\n\t\tFACTOR DE COMPRESIÓN\t\tRAZÓN DE COMPRESIÓN\t\tPORCENTAJE DE REDUCCIÓN");
            Console.WriteLine("\t\t" + compression_factor + "\t\t" + compression_ratio + "\t\t" + reduction_percentage);


            Console.ReadLine();
        }
Example #9
0
        public void Post([FromForm(Name = "file")] IFormFile file, string name, string method)
        {
            //lectura del archivo
            var result = new StringBuilder();

            using (var reader = new StreamReader(file.OpenReadStream()))
            {
                while (reader.Peek() >= 0)
                {
                    result.AppendLine(reader.ReadLine());
                }
            }
            byte[] textInBytes = Encoding.ASCII.GetBytes(result.ToString());

            //ejecuta según el método de compresión escogido
            if (method.ToLower().Equals("huffman"))
            {
                Huffman compressMethods = new Huffman();
                compressMethods.BuildHuffman(textInBytes, name);
                compressMethods.WriteFile(textInBytes, name, file.FileName);
            }
            else if (method.ToLower().Equals("lzw"))
            {
                LZW compressMethods = new LZW();
                //compressMethods.GetText(result);
                //compressMethods.InitializeDictionary(name);
                compressMethods.InitializeDictionary(textInBytes, name);
                //compressMethods.Compress(textInBytes, name, file.FileName);
                compressMethods.BuildLZW(textInBytes, name, file.FileName);
            }
        }
        public async Task <IActionResult> PostCompressAsync([FromForm] IFormFile file, string name)
        {
            try
            {
                int i            = 1;
                var originalname = name;
                if (!Directory.Exists($"{Environment.ContentRootPath}/Uploads/"))
                {
                    Directory.CreateDirectory($"{Environment.ContentRootPath}/Uploads/");
                }
                while (System.IO.File.Exists($"{Environment.ContentRootPath}/Uploads/{name}"))
                {
                    name = originalname + "(" + i.ToString() + ")";
                    i++;
                }
                await Storage.Instance.lzwCompre.CompressFile(Environment.ContentRootPath, file, name);

                var LZWInfo = new LZW();
                LZWInfo.SetAttributes(Environment.ContentRootPath, file.FileName, name);
                Storage.Instance.HistoryList.Add(LZWInfo);

                return(PhysicalFile($"{Environment.ContentRootPath}/Compressions/{name}.lzw", MediaTypeNames.Text.Plain, $"{name}.lzw"));
            }
            catch
            {
                return(StatusCode(500));
            }
        }
        public async Task <ActionResult> Decompress([FromForm] IFormFile file)
        {
            string path         = _env.ContentRootPath;
            string OriginalName = file.FileName;

            OriginalName = OriginalName.Substring(0, OriginalName.Length - 4);
            string downloadPath = path + @"\Compressions\" + OriginalName;

            byte[] FileBytes;
            try
            {
                if (file != null)
                {
                    using (FileStream fs = System.IO.File.Create(downloadPath))
                    {
                        await file.CopyToAsync(fs);
                    }
                    LZW Compressor = new LZW(downloadPath);
                    FileBytes = Compressor.Decompress(downloadPath, 100);
                    return(File(FileBytes, "text/plain", Compressor.Name));;
                }
                else
                {
                    return(StatusCode(500));
                }
            }
            catch (Exception)
            {
                return(StatusCode(500));
            }
        }
Example #12
0
        public void DescomprimirLZW([FromForm] IFormFile Nombre)
        {
            LZW LZW   = new LZW();
            var arch  = Path.GetFullPath(Nombre.FileName);
            var arch1 = new FileStream(arch, FileMode.Open);

            LZW.descompression(Nombre.FileName);
        }
Example #13
0
        public ActionResult SubirArchivo(HttpPostedFileBase file, string persona)
        {
            try
            {
                string token        = HttpContext.Request.Cookies["userID"].Value;
                int    cifradoValue = Int16.Parse(HttpContext.Request.Cookies["cifrado"].Value);

                //Subir archivo al servidor
                string path = Path.Combine(Directories.directorioUploads, Path.GetFileName(file.FileName) ?? "");
                UploadFile(path, file);

                //Comprimir
                string rutaComprimido = LZW.comprimirArchivo(path, Directories.directorioTemporal);

                //Cifrar
                SDES   cipher      = new SDES();
                string rutaCifrado = cipher.CifrarArchivo(rutaComprimido, Directories.directorioArchivos, cifradoValue);

                //Pasar ruta como parametro
                string rutaAmigable = rutaCifrado.Replace("/", "~");
                rutaAmigable = rutaAmigable.Replace(@"\", "~");

                string mensaje = $"<a href=\"/Chat/Descargar?path={rutaAmigable}\" onclick=\"clickAndDisable(this);\">{file.FileName}</a>";

                MensajeModelo nuevo = new MensajeModelo();
                nuevo.mensaje   = cipher.CifrarTexto(mensaje, cifradoValue);
                nuevo.receptor  = persona;
                nuevo.receptor  = nuevo.receptor.Replace(" ", "");
                nuevo.esArchivo = true;

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://localhost:44316/api/chat");
                    client.DefaultRequestHeaders.Authorization =
                        new AuthenticationHeaderValue("Bearer", token);

                    var postJob = client.PostAsJsonAsync <MensajeModelo>("chat", nuevo);
                    postJob.Wait();

                    var postResult = postJob.Result;
                    if (postResult.IsSuccessStatusCode)
                    {
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        return(RedirectToAction("Login", "Login"));
                    }
                }

                return(RedirectToAction("Index", "Chat"));
            }
            catch (Exception e)
            {
                return(RedirectToAction("Login", "Login"));
            }
        }
Example #14
0
        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)));
        }
Example #15
0
 private void encodeResult(object sender, RoutedEventArgs e)
 {
     text        = messageTextBox.Text.ToCharArray(0, messageTextBox.Text.Length);
     dictionary  = LZW.InitializeDictionary(text);
     alphabet    = new Dictionary <string, int>(dictionary);
     encodeList  = LZW.Encode(dictionary, text);
     result.Text = String.Join(", ", encodeList);
     CreateDictionary(dictionary);
 }
Example #16
0
        public void PostCompresionLZW([FromForm] IFormFile Nombre)
        {
            LZW LZW   = new LZW();
            var arch  = Path.GetFullPath(Nombre.FileName);
            var arch1 = new FileStream(arch, FileMode.Open);

            LZW.dictionary_initial(arch1);
            LZW.compression_process(arch1, arch);
        }
        private static void RunLZW(string text)
        {
            List <int> compressed = LZW.Compress(text);

            Console.WriteLine(string.Join(", ", compressed));
            string decompressed = LZW.Decompress(compressed);

            Console.WriteLine(decompressed);
            Console.WriteLine($"text.Length: {text.Length}, compressed.Length: {compressed.Count}");
        }
Example #18
0
    public static void Main(System.String [] args)
    {
        FileInput   c;
        ArithCoding lz;
        LZW         lz78;
        int         i, j;

        Byte [] blk;
        int     abs;

        c   = new FileInput(args [1]);
        blk = new Byte [64 * 1024];
        abs = 0;
        for (j = 0; j < c.getSize(); j++)
        {
            int k;
            int len;
            int rem;

            len = 64 * 1024;
            rem = c.getSize() - j;
            len = (len < rem ? len : rem);
            for (k = 0; k < len; k++)
            {
                blk [k] = c.getByte(k);
            }

            j += len;

            lz78 = new LZW(13);
            for (i = 0; i < len; i++)
            {
                //System.Console.Write ("\r" + (i * 100 / c.getSize ()) + ", " + lz78.getSize ());
                lz78.encode((char)blk [i]);
            }

            lz78.done();
            //System.Console.WriteLine ("Compressed " + lz78.getSize () + " Bytes");

            //System.Console.WriteLine ("LZ78...");
            lz = new ArithCoding();
            for (i = 0; i < lz78.getSize(); i++)
            {
                //System.Console.Write ("\r" + (i * 100 / lz78.getSize ()) + ", " + lz.getSize ());
                lz.encode((char)lz78.getByte(i));
            }

            lz.done();
            abs += lz.getSize();

            System.Console.Write("\r" + (j * 100 / c.getSize()) + "% (" + (float)len / lz.getSize() + ")");
        }

        System.Console.WriteLine("Compressed to " + abs + " bytes...");
    }
Example #19
0
        public void Decompress_Decompresses_Decompressed()
        {
            var lzw    = new LZW();
            var input  = new MemoryStream(new byte[] { 1, 0, 192, 192, 32, 64, 12, 15, 1, 3, 0, 193, 16, 16, 16 });
            var output = new MemoryStream();

            byte[] expected = { 1, 2, 5, 1, 7, 2, 6, 1, 2, 5, 2, 7, 1, 2, 1 };
            lzw.Decompress(input, output);
            byte[] result = output.ToArray();
            CollectionAssert.AreEqual(expected, result);
        }
Example #20
0
        public void Compress0_Compresses_Compressed()
        {
            var lzw    = new LZW();
            var input  = new MemoryStream(new byte[] { 1, 2, 5, 7, 6, 4 });
            var output = new MemoryStream();

            byte[] expected = { 1, 0, 192, 192, 128, 56, 32 };
            lzw.Compress(input, output);
            byte[] result = output.ToArray();
            CollectionAssert.AreEqual(expected, result);
        }
Example #21
0
        public void Decompress1_Decompresses_Decompressed()
        {
            var lzw    = new LZW();
            var input  = new MemoryStream(new byte[] { 1, 0, 224, 48, 48, 32 });
            var output = new MemoryStream();

            byte[] expected = { 1, 2, 1, 2, 1, 2, 1, 2 };
            lzw.Decompress(input, output);
            byte[] result = output.ToArray();
            CollectionAssert.AreEqual(expected, result);
        }
Example #22
0
        public void Compress2_Compresses_Compressed()
        {
            var lzw    = new LZW();
            var input  = new MemoryStream(new byte[] { 115, 105, 114, 32, 115, 105, 100, 32, 101, 97, 115, 116, 109, 97, 110, 32, 101, 97, 115, 105, 108, 121, 32, 116, 101, 97, 115, 101, 115, 32, 115, 101, 97, 32, 115, 105, 99, 107, 32, 115, 101, 97, 108, 115 });
            var output = new MemoryStream();

            byte[] expected = { 58, 26, 142, 98, 24, 9, 148, 66, 102, 49, 29, 14, 166, 227, 17, 190, 15, 9, 53, 27, 79, 66, 19, 172, 32, 232, 102, 58, 65, 33, 16, 67, 81, 144, 217, 26, 49, 27, 92, 192 };
            lzw.Compress(input, output);
            byte[] result = output.ToArray();
            CollectionAssert.AreEqual(expected, result);
        }
Example #23
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.Default;
            Console.WriteLine($"\u001b[38;2;128;20;196m\u2580\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588\u2589\u258A\u258B\u258C\u258D\u258E\u258F\u2590\u2591\u2592\u2593\u2594\u2595\u2596\u2597\u2598\u2599\u259A\u259B\u259C\u259D\u259E\u259F\u2615\u26Be\u001b[38;2;128;128;128m");
            Console.WriteLine($"\u001b[38;2;128;20;196m\u2580\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588\u2589\u258A\u258B\u258C\u258D\u258E\u258F\u2590\u2591\u2592\u2593\u2594\u2595\u2596\u2597\u2598\u2599\u259A\u259B\u259C\u259D\u259E\u259F\u2615\u26Be\u001b[38;2;128;128;128m");
            Console.WriteLine($"\u001b[38;2;128;20;196m\u2580\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588\u2589\u258A\u258B\u258C\u258D\u258E\u258F\u2590\u2591\u2592\u2593\u2594\u2595\u2596\u2597\u2598\u2599\u259A\u259B\u259C\u259D\u259E\u259F\u2615\u26Be\u001b[38;2;170;170;170m");
            Console.WriteLine("▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟☕⚾");

            MP3 mp3 = new MP3();

            //mp3.Decode($@"C:\Users\johnr\Downloads\MBR\warez.zip\Mp3\Contra.mp3");
            mp3.Decode($@"C:\Users\johnr\Documents\outputWave1-ABR-192.mp3");
            return;

            DirectoryInfo directoryInfo = new DirectoryInfo($@"c:\users\johnr\pictures");
            //foreach (var file in directoryInfo.GetFiles())
            //{
            //    if (new string[] { ".jpg", ".jpeg", ".jfif" }.Contains(file.Extension.ToLower()))
            //    {
            //        Console.WriteLine($"File: {file.FullName}");
            //        JPEG jpg = new JPEG(file.FullName);
            //    }
            //}

            //JPEG jpeg = new JPEG($@"c:\users\johnr\pictures\Calculator1.jpg");
            JPEG jpeg = new JPEG($@"c:\users\johnr\pictures\68518b2cd5485d576cc34355ffb0027d.jpg");

            return;

            GIF gif = new GIF($@"c:\users\johnr\pictures\Calculator1.gif");

            LZW lzw = new LZW();

            BMP bmp = new BMP($@"c:\users\johnr\pictures\3Sphere_2c.bmp");

            directoryInfo = new DirectoryInfo($@"c:\users\johnr\pictures");
            foreach (var file in directoryInfo.GetFiles())
            {
                if (file.Extension.ToLower() == ".png")
                {
                    Console.WriteLine($"File: {file.FullName}");
                    PNG png        = new PNG(file.FullName);
                    var header     = png.DataChunks.Where(x => x.ChunkType.ToLower() == "ihdr").FirstOrDefault();
                    var properties = (header.DataChunkRepresentation as PNG.DataChunk.HeaderChunkRepresentation).ToProperties(header.Data);
                    //if ((byte)properties["ColorType"].Value == 6)
                    //    Console.ReadLine();
                }
            }
            //Console.WriteLine("Enter PNG Filename:");
            //string path = Console.ReadLine();
            //PNG png = new PNG(path);
        }
Example #24
0
        public static string[] DecompressFile(string filePath)
        {
            LZW          Compresor_lzw  = new LZW();
            FileStream   file           = new FileStream(filePath, FileMode.OpenOrCreate);
            BinaryReader Lector         = new BinaryReader(file);
            int          Cant_Byte_Read = 10000;
            int          Aumentar_Max   = 1;

            byte[] Text = new byte[Cant_Byte_Read];
            Text = Lector.ReadBytes(Cant_Byte_Read);
            while (file.Position < file.Length)
            {
                byte[] Aux = Lector.ReadBytes(Cant_Byte_Read);
                Array.Resize(ref Text, Text.Length + Aux.Length);
                Aux.CopyTo(Text, Cant_Byte_Read * Aumentar_Max);
                Aumentar_Max++;
            }
            Lector.Close();

            byte[] TextoComprimido = Text;
            int    cant_CName      = TextoComprimido[0];
            string Name_Original   = "";

            for (int i = 1; i <= cant_CName; i++)
            {
                Name_Original += Convert.ToChar(TextoComprimido[i]);
            }
            byte[] Data_retorna = new byte[TextoComprimido.Length - (cant_CName + 1)];
            Array.Copy(TextoComprimido, (cant_CName + 1), Data_retorna, 0, Data_retorna.Length);

            byte[] Impresor      = Compresor_lzw.Descompresion(Data_retorna);
            string FinalFileName = Directory.GetCurrentDirectory() + "\\Decompressed\\" + Name_Original;
            var    extension     = FinalFileName.Split('.');
            string ext           = extension[extension.Length - 1];
            string name          = Name_Original.Substring(0, Name_Original.Length - ext.Length - 1);
            int    count         = 0;

            while (File.Exists(FinalFileName))
            {
                count++;
                FinalFileName = Directory.GetCurrentDirectory() + "\\Decompressed\\" + name + count + "." + ext;
            }
            FileStream   archivo  = new FileStream(FinalFileName, FileMode.OpenOrCreate);
            BinaryWriter Escritor = new BinaryWriter(archivo);

            Escritor.Write(Impresor);
            Escritor.Close();
            File.Delete(filePath);
            string[] names = { Name_Original, FinalFileName };
            return(names);
        }
Example #25
0
        public void EncodeTest()
        {
            MockEncoder encoder = new MockEncoder();
            LZW         lzw     = new LZW(encoder);

            lzw.Encode((42));
            lzw.Encode((43));
            lzw.Encode((42));
            lzw.Encode((43));
            lzw.Encode((44));
            Assert.AreEqual(encoder.values[0], 42);
            Assert.AreEqual(encoder.values[1], 43);
            Assert.AreEqual(encoder.values[2], 256);
        }
Example #26
0
        public void DecodeTest()
        {
            MockEncoder encoder = new MockEncoder();

            encoder.values.Add(42);
            encoder.values.Add(43);
            encoder.values.Add(256);
            LZW lzw = new LZW(encoder);

            Assert.AreEqual(42, lzw.Decode());
            Assert.AreEqual(43, lzw.Decode());
            Assert.AreEqual(42, lzw.Decode());
            Assert.AreEqual(43, lzw.Decode());
        }
Example #27
0
        public void Descomprimir()
        {
            string descomprimido = "";
            string directorio;

            directorio = root + @"\\Upload\\";
            if (!Directory.Exists(directorio + "\\Compresion\\"))
            {
                DirectoryInfo di = Directory.CreateDirectory(directorio + "\\Compresion\\");
            }
            string     comprimido     = System.IO.File.ReadAllText(@path);
            const int  bufferLength   = 100;
            List <int> bytedecompress = new List <int>();

            var buffer = new char[bufferLength];

            using (var file = new FileStream(path, FileMode.Open))
            {
                using (var reader = new BinaryReader(file))
                {
                    while (reader.BaseStream.Position != reader.BaseStream.Length)
                    {
                        buffer = reader.ReadChars(bufferLength);
                        foreach (var item in buffer)
                        {
                            bytedecompress.Add((int)Convert.ToChar(item));
                        }
                    }
                }
            }

            descomprimido = LZW.Descompresion(bytedecompress);
            string rootRazonFactor = root;

            NombreTemporal = NombreTemporal.Replace(".lzw", "");
            root           = root + @"\\Upload\\Compresion\\" + NombreTemporal + ".txt";
            File.WriteAllText(@root, descomprimido);
            FactorCompresion     = Convert.ToDouble(comprimido.Length) / Convert.ToDouble(descomprimido.Length);
            RazonCompresion      = Convert.ToDouble(descomprimido.Length) / Convert.ToDouble(comprimido.Length);
            PorcentajeCompresion = ((FactorCompresion / RazonCompresion) * 100);
            double raz     = Math.Round(RazonCompresion, 2);
            double fac     = Math.Round(FactorCompresion, 2);
            double porcent = Math.Round(PorcentajeCompresion, 2);

            rootRazonFactor = rootRazonFactor + @"\\Upload\\Compresion\\FactorRazon.txt";
            File.WriteAllText(@rootRazonFactor, "Razon de compresión: " + raz.ToString() + Environment.NewLine + "Factor de compresión: " + fac.ToString() + Environment.NewLine + "Porcentaje de compresión: " + porcent.ToString() + "%");
        }
        public ActionResult ComprimirLZW(HttpPostedFileBase file)
        {
            try
            {
                string path = Path.Combine(directorioUploads, Path.GetFileName(file.FileName));

                UploadFile(path, file);
                LZW.comprimir(path);
            }
            catch (Exception ex)
            {
                ViewBag.Message = "ERROR:" + ex.Message;
                throw;
            }

            return(RedirectToAction("Index"));
        }
Example #29
0
        public string Post(IFormFile file, string name)
        {
            LZW.Compresion(file, name);
            var NewFile = new FileInfo(Path.Combine(Environment.CurrentDirectory, "Compressions", $"{name}.lzw"));

            CompressionsCollections.EscrituraCompresiones(
                new CompressionsCollections
            {
                Nombre_Del_Archivo_Original   = file.FileName,
                Nombre_Del_Archivo_Comprimido = $"{name}.lzw",
                Ruta_Del_Archivo_Comprimido   = Path.Combine(Environment.CurrentDirectory, "Compressions", $"{name}.lzw"),
                Razon_De_Compresion           = (double)NewFile.Length / (double)file.Length,
                Factor_De_Compresion          = (double)file.Length / (double)NewFile.Length,
                Porcentaje = 100 - (((double)NewFile.Length / (double)file.Length) * 100)     // correccion del anterior (lab03), se muestra el porcentaje de reduccion real
            });
            return("Archivo Compreso en :" + NewFile.ToString());
        }
Example #30
0
    /**/ public static void main(string[] strarr)
    {
        if (java.lang.String.instancehelper_equals(strarr[0], "-"))
        {
            LZW.compress();
        }
        else
        {
            if (!java.lang.String.instancehelper_equals(strarr[0], "+"))
            {
                string arg_36_0 = "Illegal command line argument";

                throw new ArgumentException(arg_36_0);
            }
            LZW.expand();
        }
    }