示例#1
0
        public static void Encode(string arquivo)
        {
            LZWEncoder encoder  = new LZWEncoder();
            string     conteudo = Arquivo.Abrir(arquivo);

            Console.WriteLine("Iniciada a compressão");
            DateTime dataInicial = DateTime.Now;

            //Codificação LZW
            string lzwEncoded = encoder.Encode(conteudo);

            HuffmanTree huffman = new HuffmanTree();

            //Criação da árvore huffman
            huffman.Build(lzwEncoded);

            //Codificação huffman
            var huffmanEncoded = huffman.Encode(lzwEncoded);

            DateTime dataFinal = DateTime.Now;

            string tempoDecorrido = (dataFinal - dataInicial).TotalSeconds.ToString("N2");

            //Contabiliza apenas os tempos para compressão. Igora tempo de IO
            Console.WriteLine($"Arquivo comprimido em {tempoDecorrido} segundos");

            byte[] ret = new byte[(huffmanEncoded.Length - 1) / 8 + 1];
            huffmanEncoded.CopyTo(ret, 0);

            //Gravando arquivo comprimido
            Arquivo.Gravar(ret, $"{arquivo.Split('.')[0]}.scps");
        }
        /**
         * Encodes and writes pixel data
         */
        protected void WritePixels()
        {
            LZWEncoder encoder =
                new LZWEncoder(width, height, indexedPixels, colorDepth);

            encoder.Encode(fs);
        }
        /// <summary>
        /// Writes to the specified writer.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <returns>
        /// True if it writes successfully, false otherwise
        /// </returns>
        public override bool Write(EndianBinaryWriter writer)
        {
            var encoder = new LZWEncoder(Indices, BitDepth);

            encoder.Encode(writer.BaseStream);
            return(true);
        }
示例#4
0
        static void Main(string[] args)
        {
            Console.WriteLine("Generate ANSI table ...");

            ANSI ascii = new ANSI();

            ascii.WriteToFile();

            Console.WriteLine("ANSI table generated.");

            Console.WriteLine("Start encoding " + fileToCompress + " ...");

            string     text    = File.ReadAllText(fileToCompress, System.Text.ASCIIEncoding.Default);
            LZWEncoder encoder = new LZWEncoder();

            byte[] b = encoder.EncodeToByteList(text);
            File.WriteAllBytes(encodedFile, b);

            Console.WriteLine("File " + fileToCompress + " encoded to " + encodedFile);

            Console.WriteLine("Start decoding " + encodedFile);

            LZWDecoder decoder = new LZWDecoder();

            byte[] bo            = File.ReadAllBytes(encodedFile);
            string decodedOutput = decoder.DecodeFromCodes(bo);

            File.WriteAllText(decodedFile, decodedOutput, System.Text.Encoding.Default);

            Console.WriteLine("File " + encodedFile + " decoded to " + decodedFile);
        }
示例#5
0
        public static int compress(byte[] origData, int offset, int length, BinaryWriter writer, CompressionMethod compId, CompressionLevel compressLevel)
        {
            if (compressLevel == CompressionLevel.NoCompression)
            {
                writer.Write(origData);
                return(origData.Length);
            }

            switch (compId)
            {
            case CompressionMethod.UNCOMPRESSED:
                writer.Write(origData);
                return(origData.Length);

            case CompressionMethod.LZW:
                var    lzwEncoder = new LZWEncoder();
                byte[] compressed = lzwEncoder.Encode(origData, offset, length);
                writer.Write(compressed);
                return(compressed.Length);

            case CompressionMethod.DEFLATE:
            case CompressionMethod.ADOBE_DEFLATE:
                writer.Write(deflateHeader(compressLevel));
                compressed = deflateCompress(origData, offset, length, compressLevel);
                writer.Write(compressed);
                var crcChecker = new Adler32();
                writer.Write(crcChecker.SwitchByteOrder(crcChecker.ComputeChecksum(origData, offset, length)));
                return(compressed.Length + 6);

            default:
                throw new ReadFileException("Unsupported comnpression");
            }
        }
示例#6
0
        private void WriteImage()
        {
            var encoder = new LZWEncoder(IndexPixels(ColorTable), ColorTableSize); //ColorTableSize+1

            encoder.Encode(InternalStream);

            //var encoder = new FileWriters.GifWriter.LzwEncoder(0, 0, IndexPixels(ColorTable), 8); //+1
            //encoder.Encode(InternalStream);
        }
示例#7
0
        public static void encode(string filename)
        {
            var fileContent  = FileWrapper.open(filename);
            var encoder      = new LZWEncoder();
            var lzwEncoded   = encoder.Encode(fileContent);
            var deltaEncoded = Delta.encode(lzwEncoded);

            FileWrapper.writeInBytes(deltaEncoded, getEncodedFilename(filename));
        }
示例#8
0
        public EncodedFile Run(SourceFile source)
        {
            var lzwEncoder     = new LZWEncoder();
            var huffmanEncoder = new HuffmanEncoder();

            var outlzw     = lzwEncoder.Encode(source.Content);
            var outHuffman = huffmanEncoder.Encode(outlzw);

            var header      = new FileHeader(Pipeline, huffmanEncoder.HuffmanMetadata, source.Extension);
            var encodedFile = new EncodedFile(header, outHuffman);

            return(encodedFile);
        }
示例#9
0
        private void btnPack_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();

            if (opf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtPath.Text = opf.FileName;

                var        text    = File.ReadAllText(opf.FileName, System.Text.ASCIIEncoding.Default);
                LZWEncoder encoder = new LZWEncoder();

                var buffer = encoder.EncodeToByteList(text);
                File.WriteAllBytes(opf.FileName + ".lzw", buffer);

                MessageBox.Show("Encoding complete.");
            }
        }
示例#10
0
        private void Compress(object sender, RoutedEventArgs e)
        {
            if (!filenameCom.fileIsEmpty())
            {
                string noteCompressed = @"D:\RealEncAndCom\noteCompressed.txt";
                File.Delete(noteCompressed);
                ANSI       ascii   = new ANSI();
                LZWEncoder encoder = new LZWEncoder();

                string text = File.ReadAllText(filenameCom, System.Text.Encoding.Default);
                ascii.WriteToFile();
                byte[] b = encoder.EncodeToByteList(text);
                File.WriteAllBytes(noteCompressed, b);
                comLabel1.Content = "Файл был сжат!";
            }
            else
            {
                comLabel1.Content = "Файл не был сжат!";
            }
        }
示例#11
0
        public static void Do()
        {
            Console.WriteLine("Generate ANSI table ...");
            var ascii = new Ansi();

            ascii.WriteToFile();
            Console.WriteLine("ANSI table generated.");
            Console.WriteLine("Start encoding " + _fileToCompress + " ...");
            var text    = File.ReadAllText(_fileToCompress);
            var encoder = new LZWEncoder();
            var b       = encoder.EncodeToByteList(text);

            File.WriteAllBytes(_encodedFile, b);
            Console.WriteLine("File " + _fileToCompress + " encoded to " + _encodedFile);
            Console.WriteLine("Start decoding " + _encodedFile);
            var decoder       = new LZWDecoder();
            var bo            = File.ReadAllBytes(_encodedFile);
            var decodedOutput = decoder.DecodeFromCodes(bo);

            File.WriteAllText(_decodedFile, decodedOutput, Encoding.Default);
            Console.WriteLine("File " + _encodedFile + " decoded to " + _decodedFile);
        }
示例#12
0
        static void SetFrames(List<GifFrame> frames,StreamHelper streamHelper,Stream fs)
        {
            foreach (GifFrame f in frames)
            {
                List<byte> list = new List<byte>();
                if (f.GraphicExtension != null)
                {
                    list.AddRange(f.GraphicExtension.GetBuffer());
                }
                f.ImageDescriptor.SortFlag = false;
                f.ImageDescriptor.InterlaceFlag = false;
                list.AddRange(f.ImageDescriptor.GetBuffer());
                if (f.ImageDescriptor.LctFlag)
                {
                    list.AddRange(f.LocalColorTable);
                }
                streamHelper.WriteBytes(list.ToArray());
                int transIndex = -1;

                if (f.GraphicExtension.TransparencyFlag)
                {
                    transIndex = f.GraphicExtension.TranIndex;
                }

                byte[] indexedPixel = GetImagePixels(f.Image, f.LocalColorTable, transIndex);

                LZWEncoder lzw = new LZWEncoder(indexedPixel, (byte)f.ColorDepth);
                lzw.Encode(fs);
                streamHelper.WriteBytes(new byte[] { 0 });
            }
            streamHelper.WriteBytes(new byte[] { 0x3B });
        }
示例#13
0
        public Frame(byte[] Pixels, int Width, int Height, uint[] Palette, uint ColorCount, LZWEncoder Encoder, ushort Delay, int TransparentColorIndex = -1)
        {
            if (Pixels == null)
            {
                throw new ArgumentException("Pixels can't be null.");
            }

            if (Width <= 0 || Height <= 0)
            {
                throw new ArgumentException("Width and Height must be greater 0.");
            }

            if (Palette == null || Palette.Length > 256)
            {
                throw new ArgumentException("Palette null or more than 256 entries.");
            }

            if (ColorCount > Palette.Length)
            {
                throw new ArgumentException("ColorCount bigger than Palette size.");
            }

            if (Encoder == null)
            {
                throw new ArgumentException("Encoder can't be null.");
            }

            // save provided dimension
            this.Width  = (ushort)Width;
            this.Height = (ushort)Height;

            // encode pixels using argument encoder instance
            Encoder.Encode(Pixels, Chunks, Width, Height);
            MinLZWCodeSize = 8;

            // determine size of colortable to use
            // get next bigger power of 2 value of used colorcount
            uint palSize2 = NextPowerOf2(ColorCount);

            // use and create local color table with determined size
            Packed.IsLocalColorTable     = true;
            Packed.SizeOfLocalColorTable = (uint)Math.Max((int)Math.Log(palSize2, 2.0) - 1, 0);
            ColorTable = new byte[palSize2 * 3];

            // fill color table
            int i = 0;

            for (uint j = 0; j < ColorCount; j++)
            {
                uint c = Palette[j];
                ColorTable[i] = (byte)((c & 0x00FF0000) >> 16); i++;
                ColorTable[i] = (byte)((c & 0x0000FF00) >> 8); i++;
                ColorTable[i] = (byte)(c & 0x000000FF); i++;
            }

            // set graphics control extension
            GraphicsControl                       = new ExtensionGraphicsControl();
            GraphicsControl.DelayTime             = Delay;
            GraphicsControl.Packed.IsUserInput    = false;
            GraphicsControl.Packed.DisposalMethod =
                ExtensionGraphicsControl.Flags.DisposalMethods.RestoreToBackground;

            // possibly set transparent color index and enable transparency
            if (TransparentColorIndex > -1 && TransparentColorIndex < 256)
            {
                GraphicsControl.Packed.IsTransparentColor = true;
                GraphicsControl.TransparentColorIndex     = (byte)TransparentColorIndex;
            }
        }