Finish() публичный Метод

Finishes the stream by calling finish() on the deflater.
/// Not all input is deflated ///
public Finish ( ) : void
Результат void
		// netz.compress.ICompress implementation

		public long Compress(string file, string zipFile)
		{
			long length = -1;
			FileStream ifs = null;
			FileStream ofs = null;
			try
			{
				ifs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
				ofs = File.Open(zipFile, FileMode.Create, FileAccess.Write, FileShare.None);
				DeflaterOutputStream dos = new DeflaterOutputStream(ofs, new Deflater(Deflater.BEST_COMPRESSION));
				byte[] buff = new byte[ifs.Length];
				while(true)
				{
					int r = ifs.Read(buff, 0, buff.Length);
					if(r <= 0) break;
					dos.Write(buff, 0, r);
				}
				dos.Flush();
				dos.Finish();
				length = dos.Length;
				dos.Close();
			}
			finally
			{
				if(ifs != null) ifs.Close();
				if(ofs != null) ofs.Close();
			}
			return length;
		}
Пример #2
0
        public void TestInflateDeflate()
        {
            MemoryStream ms = new MemoryStream();
            Deflater deflater = new Deflater(6);
            DeflaterOutputStream outStream = new DeflaterOutputStream(ms, deflater);

            byte[] buf = new byte[1000000];
            System.Random rnd = new Random();
            rnd.NextBytes(buf);

            outStream.Write(buf, 0, buf.Length);
            outStream.Flush();
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            InflaterInputStream inStream = new InflaterInputStream(ms);
            byte[] buf2 = new byte[buf.Length];
            int    pos  = 0;
            while (true) {
                int numRead = inStream.Read(buf2, pos, 4096);
                if (numRead <= 0) {
                    break;
                }
                pos += numRead;
            }

            for (int i = 0; i < buf.Length; ++i) {
                Assertion.AssertEquals(buf2[i], buf[i]);
            }
        }
Пример #3
0
 public static byte[] CompressZlib(byte[] input)
 {
     MemoryStream m = new MemoryStream();
     DeflaterOutputStream zipStream = new DeflaterOutputStream(m, new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(8));
     zipStream.Write(input, 0, input.Length);
     zipStream.Finish();
     return m.ToArray();
 }
Пример #4
0
		internal static Byte[] Deflate(Byte[] b)
		{
			System.IO.MemoryStream ms = new System.IO.MemoryStream();
			DeflaterOutputStream outStream =new DeflaterOutputStream( ms);
			
			outStream.Write(b, 0, b.Length);
			outStream.Flush();
			outStream.Finish();
			
			Byte[] result=ms.ToArray();
			outStream.Close();
			ms.Close();
			return result;
		}
Пример #5
0
        /*
         * Name function: Compress
         * Purpose: compress a part of the byte array into a Zlib Block
         * Input: - buffer: byte array
         *        - offset: starting offset inside the array
         *        - count: num of bytes to compress starting from the offset
         * 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, int offset, int count)
        {
            if(buffer == null)
                throw new ArgumentNullException();
            if (count < 0)
                throw new FormatException();
            if (offset + count > buffer.Length)
                throw new IndexOutOfRangeException();

            MemoryStream headBlock = new MemoryStream();
            MemoryStream dataBlock = new MemoryStream();
            DeflaterOutputStream zipStream;

            int numSeg = (int)Math.Ceiling((double)count / (double)maxSegmentSize);

            headBlock.WriteValueU32(magic);
            headBlock.WriteValueU32(maxSegmentSize);
            headBlock.WriteValueU32(0x0);            //total compressed size, still to calculate
            headBlock.WriteValueS32(count);          //total uncompressed size

            for (int i = count; i > 0; i -= (int)maxSegmentSize)
            {
                int copyBytes = Math.Min(i, (int)maxSegmentSize);
                uint precCompSize = (uint)dataBlock.Length;
                zipStream = new DeflaterOutputStream(dataBlock);
                zipStream.Write(buffer, offset + (count - i), copyBytes);
                zipStream.Flush();
                zipStream.Finish();
                headBlock.WriteValueU32((uint)dataBlock.Length - precCompSize); //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;
        }
Пример #6
0
 /// <summary>
 /// ѹ�����ݣ����ѹ����ֵΪ-1��ʾ��������������ѹ������
 /// </summary>
 /// <param name="val">ԭʼ������</param>
 /// <returns>ѹ����������</returns>
 public byte[] Compress(byte[] val)
 {
     byte[] buf;
     if (overSize != -1 && val.Length > overSize) {
         using (MemoryStream destStream = new MemoryStream()) {
             Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
             using (DeflaterOutputStream compressStream = new DeflaterOutputStream(destStream, deflater)) {
                 compressStream.Write(val, 0, val.Length);
                 compressStream.Finish();
                 buf = new byte[destStream.Length + 1];
                 destStream.ToArray().CopyTo(buf, 1);
             }
             buf[0] = 1; // ��ѹ����־
             return buf;
         }
     }
     else {
         buf = new byte[val.Length + 1];
         val.CopyTo(buf, 1);
         buf[0] = 0; // δѹ����־
         return buf;
     }
 }
Пример #7
0
        /// <summary>
        /// Compresses data using zlib.
        /// </summary>
        /// <param name="data">The data to compress</param>
        /// <returns>A byte array containing the compressed data</returns>
        public static byte[] Compress(string data)
        {
            // Commented out below as it loses extended ASCII (127+) and replaces with a ?
            // byte[] bytes = ASCIIEncoding.ASCII.GetBytes(data);

            // Encoding using default terminal extended ascii codepage 437
            byte[] bytes = Encoding.GetEncoding(437).GetBytes(data);
            byte[] returnBytes;
            using (var stream = new MemoryStream())
            {
                using (var compressedStream = new DeflaterOutputStream(stream))
                {
                    compressedStream.Write(bytes, 0, bytes.Length);
                    compressedStream.Finish();
                    stream.Position = 0;

                    returnBytes = new byte[stream.Length];
                    stream.Read(returnBytes, 0, returnBytes.Length);
                }
            }

            return returnBytes;
        }
Пример #8
0
        /// <summary>
        /// Creates the static library.
        /// </summary>
        /// <param name='dataFile'>
        /// Data file.
        /// </param>
        /// <param name='needZeroEnd'>
        /// Need zero end.
        /// </param>
        public void CreateStaticLibrary(String dataFile, bool needZeroEnd)
        {
            // Generate the pretty name
            this.SymbolName = GetSymbolName (dataFile);

            // If we need a zero at the end (for text files), add 1 byte
            int size = (int)new FileInfo (dataFile).Length;
            byte[] fileBuffer = File.ReadAllBytes (dataFile);

            this.Logger.LogInfo ("Embedding '" + dataFile + "'...");

            // Use raw file
            this.InputSize = size;
            byte[] dataBuffer = fileBuffer;
            if (this.Compress) {
                // Compress the data file if required
                using (MemoryStream stream = new MemoryStream()) {
                    using (DeflaterOutputStream deflate = new DeflaterOutputStream(stream)) {
                        int n = 0, len = 0;
                        while (n < size) {
                            len = Math.Min (size - n, CHUNK);
                            deflate.Write (fileBuffer, n, len);
                            n += CHUNK;
                        }
                        if (needZeroEnd) {
                            deflate.WriteByte (0);
                        }
                        deflate.Finish ();
                    }
                    dataBuffer = stream.ToArray ();
                    stream.Close ();
                }
            } else if (needZeroEnd) {
                this.InputSize = size + 1;
                dataBuffer = new byte[this.InputSize];
                Array.Copy(fileBuffer, dataBuffer, size);
                dataBuffer[size] = 0;
            }
            this.OutputSize = dataBuffer.Length;

            if (this.Compress) {
                this.Logger.LogInfo ("Compression ratio: " + Math.Floor(100.0 * this.OutputSize / this.InputSize) + "%");
            }

            // Compute the names
            String sFile = Path.Combine (this.OutputDirectory, this.SymbolName + ".s");
            String oFile = Path.Combine (this.OutputDirectory, this.SymbolName + ".o");
            String aFile = Path.Combine (this.OutputDirectory, this.SymbolName + ".a");
            this.OutputFile = Path.Combine (this.OutputDirectory, "lib" + this.SymbolName + ".a");

            // (1) Create the assembly source file
            this.Logger.LogDebug ("Create assembly file '" + Path.GetFileName (sFile) + "'...");
            String content = String.Format (CultureInfo.CurrentCulture, TEMPLATE, this.SymbolName, this.OutputSize, SPACER_BYTE);
            File.WriteAllText (sFile, content);

            // (2) Create the object file
            this.Logger.LogDebug ("Create object file '" + Path.GetFileName (oFile) + "'...");
            using (ProcessHelper helper = new ProcessHelper("cc", string.Format("{0} -c -o \"{1}\" \"{2}\"", this.ArchitectureFlags ?? String.Empty, oFile, sFile))) {
                helper.Logger = this.Logger;
                helper.Execute ();
            }

            // (3) Create the static library
            this.Logger.LogDebug ("Create library file '" + Path.GetFileName (aFile) + "'...");
            using (ProcessHelper helper = new ProcessHelper("libtool", string.Format("-o \"{0}\" \"{1}\"", aFile, oFile))) {
                helper.Logger = this.Logger;
                helper.Execute ();
            }

            // (4) Swap binary content
            this.Logger.LogDebug ("Swaping content to '" + Path.GetFileName (this.OutputFile) + "'...");

            // Not quite memory-efficient, but simpler to code
            byte[] outputBuffer = File.ReadAllBytes (aFile);

            // Search for the beginning and the end of the spacer zone
            int start = Locate (outputBuffer, new[] {SPACER_BYTE, SPACER_BYTE, SPACER_BYTE, SPACER_BYTE});

            // Insert the data file content into the static library
            Array.Copy (dataBuffer, 0, outputBuffer, start, dataBuffer.Length);

            // Write the result on the disk
            File.WriteAllBytes (this.OutputFile, outputBuffer);
        }
Пример #9
0
	static void GenerateBundles (ArrayList files)
	{
		string temp_s = "temp.s"; // Path.GetTempFileName ();
		string temp_c = "temp.c";
		string temp_o = "temp.o";

		if (compile_only)
			temp_c = output;
		if (object_out != null)
			temp_o = object_out;
		
		try {
			ArrayList c_bundle_names = new ArrayList ();
			ArrayList config_names = new ArrayList ();
			byte [] buffer = new byte [8192];

			using (StreamWriter ts = new StreamWriter (File.Create (temp_s))) {
			using (StreamWriter tc = new StreamWriter (File.Create (temp_c))) {
			string prog = null;

			tc.WriteLine ("/* This source code was produced by mkbundle, do not edit */");
			tc.WriteLine ("#include <mono/metadata/assembly.h>\n");

			if (compress) {
				tc.WriteLine ("typedef struct _compressed_data {");
				tc.WriteLine ("\tMonoBundledAssembly assembly;");
				tc.WriteLine ("\tint compressed_size;");
				tc.WriteLine ("} CompressedAssembly;\n");
			}

			foreach (string url in files){
				string fname = new Uri (url).LocalPath;
				string aname = Path.GetFileName (fname);
				string encoded = aname.Replace ("-", "_").Replace (".", "_");

				if (prog == null)
					prog = aname;
				
				Console.WriteLine ("   embedding: " + fname);
				
				Stream stream = File.OpenRead (fname);

				long real_size = stream.Length;
				int n;
				if (compress) {
					MemoryStream ms = new MemoryStream ();
					DeflaterOutputStream deflate = new DeflaterOutputStream (ms);
					while ((n = stream.Read (buffer, 0, 8192)) != 0){
						deflate.Write (buffer, 0, n);
					}
					stream.Close ();
					deflate.Finish ();
					byte [] bytes = ms.GetBuffer ();
					stream = new MemoryStream (bytes, 0, (int) ms.Length, false, false);
				}

				WriteSymbol (ts, "assembly_data_" + encoded, stream.Length);

				while ((n = stream.Read (buffer, 0, 8192)) != 0){
					for (int i = 0; i < n; i++){
						ts.Write ("\t.byte {0}\n", buffer [i]);
					}
				}
				ts.WriteLine ();

				if (compress) {
					tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
					tc.WriteLine ("static CompressedAssembly assembly_bundle_{0} = {{{{\"{1}\"," +
							" assembly_data_{0}, {2}}}, {3}}};",
						      encoded, aname, real_size, stream.Length);
					double ratio = ((double) stream.Length * 100) / real_size;
					Console.WriteLine ("   compression ratio: {0:.00}%", ratio);
				} else {
					tc.WriteLine ("extern const unsigned char assembly_data_{0} [];", encoded);
					tc.WriteLine ("static const MonoBundledAssembly assembly_bundle_{0} = {{\"{1}\", assembly_data_{0}, {2}}};",
						      encoded, aname, real_size);
				}
				stream.Close ();

				c_bundle_names.Add ("assembly_bundle_" + encoded);

				try {
					FileStream cf = File.OpenRead (fname + ".config");
					Console.WriteLine (" config from: " + fname + ".config");
					tc.WriteLine ("extern const unsigned char assembly_config_{0} [];", encoded);
					WriteSymbol (ts, "assembly_config_" + encoded, cf.Length);
					while ((n = cf.Read (buffer, 0, 8192)) != 0){
						for (int i = 0; i < n; i++){
							ts.Write ("\t.byte {0}\n", buffer [i]);
						}
					}
					ts.WriteLine ();
					config_names.Add (new string[] {aname, encoded});
				} catch (FileNotFoundException) {
					/* we ignore if the config file doesn't exist */
				}

			}
			if (config_file != null){
				FileStream conf;
				try {
					conf = File.OpenRead (config_file);
				} catch {
					Error (String.Format ("Failure to open {0}", config_file));
					return;
				}
				Console.WriteLine ("System config from: " + config_file);
				tc.WriteLine ("extern const unsigned char system_config;");
				WriteSymbol (ts, "system_config", config_file.Length);

				int n;
				while ((n = conf.Read (buffer, 0, 8192)) != 0){
					for (int i = 0; i < n; i++){
						ts.Write ("\t.byte {0}\n", buffer [i]);
					}
				}
				// null terminator
				ts.Write ("\t.byte 0\n");
				ts.WriteLine ();
			}

			if (machine_config_file != null){
				FileStream conf;
				try {
					conf = File.OpenRead (machine_config_file);
				} catch {
					Error (String.Format ("Failure to open {0}", machine_config_file));
					return;
				}
				Console.WriteLine ("Machine config from: " + machine_config_file);
				tc.WriteLine ("extern const unsigned char machine_config;");
				WriteSymbol (ts, "machine_config", machine_config_file.Length);

				int n;
				while ((n = conf.Read (buffer, 0, 8192)) != 0){
					for (int i = 0; i < n; i++){
						ts.Write ("\t.byte {0}\n", buffer [i]);
					}
				}
				// null terminator
				ts.Write ("\t.byte 0\n");
				ts.WriteLine ();
			}
			ts.Close ();
			
			Console.WriteLine ("Compiling:");
			string cmd = String.Format ("{0} -o {1} {2} ", GetEnv ("AS", "as"), temp_o, temp_s);
			int ret = Execute (cmd);
			if (ret != 0){
				Error ("[Fail]");
				return;
			}

			if (compress)
				tc.WriteLine ("\nstatic const CompressedAssembly *compressed [] = {");
			else
				tc.WriteLine ("\nstatic const MonoBundledAssembly *bundled [] = {");

			foreach (string c in c_bundle_names){
				tc.WriteLine ("\t&{0},", c);
			}
			tc.WriteLine ("\tNULL\n};\n");
			tc.WriteLine ("static char *image_name = \"{0}\";", prog);

			tc.WriteLine ("\nstatic void install_dll_config_files (void) {\n");
			foreach (string[] ass in config_names){
				tc.WriteLine ("\tmono_register_config_for_assembly (\"{0}\", assembly_config_{1});\n", ass [0], ass [1]);
			}
			if (config_file != null)
				tc.WriteLine ("\tmono_config_parse_memory (&system_config);\n");
			if (machine_config_file != null)
				tc.WriteLine ("\tmono_register_machine_config (&machine_config);\n");
			tc.WriteLine ("}\n");

			if (config_dir != null)
				tc.WriteLine ("static const char *config_dir = \"{0}\";", config_dir);
			else
				tc.WriteLine ("static const char *config_dir = NULL;");

			Stream template_stream;
			if (compress) {
				template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_z.c");
			} else {
				template_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template.c");
			}

			StreamReader s = new StreamReader (template_stream);
			string template = s.ReadToEnd ();
			tc.Write (template);

			if (!nomain) {
				Stream template_main_stream = Assembly.GetAssembly (typeof(MakeBundle)).GetManifestResourceStream ("template_main.c");
				StreamReader st = new StreamReader (template_main_stream);
				string maintemplate = st.ReadToEnd ();
				tc.Write (maintemplate);
			}
			
			tc.Close ();

			if (compile_only)
				return;

			string zlib = (compress ? "-lz" : "");
			string debugging = "-g";
			string cc = GetEnv ("CC", IsUnix ? "cc" : "gcc -mno-cygwin");

			if (style == "linux")
				debugging = "-ggdb";
			if (static_link) {
				string smonolib;
				if (style == "osx")
					smonolib = "`pkg-config --variable=libdir mono-2`/libmono-2.0.a ";
				else
					smonolib = "-Wl,-Bstatic -lmono-2.0 -Wl,-Bdynamic ";
				cmd = String.Format ("{4} -o {2} -Wall `pkg-config --cflags mono-2` {0} {3} " +
						     "`pkg-config --libs-only-L mono-2` " + smonolib +
						     "`pkg-config --libs-only-l mono-2 | sed -e \"s/\\-lmono-2.0 //\"` {1}",
						     temp_c, temp_o, output, zlib, cc);
			} else {
				
				cmd = String.Format ("{4} " + debugging + " -o {2} -Wall {0} `pkg-config --cflags --libs mono-2` {3} {1}",
						     temp_c, temp_o, output, zlib, cc);
			}
                            
			ret = Execute (cmd);
			if (ret != 0){
				Error ("[Fail]");
				return;
			}
			Console.WriteLine ("Done");
			}
			}
		} finally {
			if (!keeptemp){
				if (object_out == null){
					File.Delete (temp_o);
				}
				if (!compile_only){
					File.Delete (temp_c);
				}
				File.Delete (temp_s);
			}
		}
	}
Пример #10
0
		protected MemoryStream CompressBuffer(byte[] buf, int index, int length)
		{

			if (length < MIN_COMPRESS_LENGTH) return null;

			MemoryStream ms = new MemoryStream(buf.Length);
			DeflaterOutputStream dos = new DeflaterOutputStream(ms);

			dos.WriteByte( (byte)(length & 0xff ));
			dos.WriteByte( (byte)((length >> 8) & 0xff ));
			dos.WriteByte( (byte)((length >> 16) & 0xff ));
			dos.WriteByte( 0 );

			dos.Write( buf, index, length );
			dos.Finish();
			if (ms.Length > length+4) return null;
			return ms;
		}
Пример #11
0
        internal string WriteObject(byte[] aContent, EObjectType aType)
        {
            byte zero = 0;
            byte space = (byte)' ';
            byte[] type = Object.TypeBytes(aType);
            byte[] length = ASCIIEncoding.ASCII.GetBytes(aContent.Length.ToString());
            byte[] obj = new byte[type.Length + length.Length + aContent.Length + 2];

            Array.Copy(type, 0, obj, 0, type.Length);
            obj[type.Length] = space;
            Array.Copy(length, 0, obj, type.Length + 1, length.Length);
            obj[type.Length + length.Length + 1] = zero;
            Array.Copy(aContent, 0, obj, type.Length + length.Length + 2, aContent.Length);

            string id = Hash.String(iHash.Compute(obj));

            DirectoryInfo folder = iFolderObjects.CreateSubdirectory(id.Substring(0, 2));

            String path = Path.Combine(folder.FullName, id.Substring(2));

            if (File.Exists(path))
            {
                return (id);
            }

            var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write);

            DeflaterOutputStream deflater = new DeflaterOutputStream(file);

            using (var writer = new BinaryWriter(deflater))
            {
                writer.Write(obj);
                deflater.Finish();
            }

            return (id);
        }
Пример #12
0
        private void writeCMV(string outFilename)
        {
            byte[] target, compressed;
            ExtensionType extension;
            DeflaterOutputStream zipOutStream;
            MemoryStream stream;
            MemoryStream memoryStream;

            cols = Columns;
            rows = Rows;

            if (frames.Count == 0)
            {
                throw new CMVException("There are no frames to save.");
            }

            if (cols == 0 || rows == 0)
            {
                throw new CMVException(String.Format("Invalid columns ({0}), rows ({1}) combination", cols, rows));
            }

            extension = checkExtension(outFilename);

            stream = new MemoryStream();

            byte[] intBytes = new byte[4];

            intBytes = BitConverter.GetBytes((Int32)version);
            stream.Write(intBytes, 0, 4);

            intBytes = BitConverter.GetBytes((Int32)cols);
            stream.Write(intBytes, 0, 4);

            intBytes = BitConverter.GetBytes((Int32)rows);
            stream.Write(intBytes, 0, 4);

            intBytes = BitConverter.GetBytes((Int32)delayRate);
            stream.Write(intBytes, 0, 4);

            // Sounds
            if (version == 10001)
            {
                intBytes = BitConverter.GetBytes((Int32)numSounds);
                stream.Write(intBytes, 0, 4);

                stream.Write(soundNames, 0, soundNames.Length);

                stream.Write(soundTimings, 0, soundTimings.Length);
            }

            //int frameSize = (int)(cols * rows);
            //frameSize += frameSize;

            byte[] chunk;
            int i = 0;
            int framesInChunk;
            int compressedChunkSize;
            byte[] frame;
            while(i < frames.Count)
            {
                if ((frames.Count - i) > FRAMES_PER_CHUNK)
                {
                    framesInChunk = FRAMES_PER_CHUNK;
                }
                else
                {
                    framesInChunk = (Int32)(frames.Count - i);
                }

                memoryStream = new MemoryStream();
                zipOutStream = new DeflaterOutputStream(memoryStream, new Deflater(Deflater.BEST_COMPRESSION));

                for (int j = 0; j < framesInChunk; j++)
                {
                    frame = frames[i + j].Frame;
                    zipOutStream.Write(frame, 0, frame.Length);
                }

                zipOutStream.Finish();

                compressedChunkSize = (Int32)memoryStream.Length;

                intBytes = BitConverter.GetBytes((Int32)compressedChunkSize);
                stream.Write(intBytes, 0, 4);

                chunk = memoryStream.ToArray();
                stream.Write(chunk, 0, chunk.Length);

                i = i + framesInChunk;

                zipOutStream.Close();
            }

            target = stream.ToArray();
            stream.Close();

            if (extension == ExtensionType.CCMV)
            {
                compressed = new byte[0];

                memoryStream = new MemoryStream(target);
                zipOutStream = new DeflaterOutputStream(memoryStream);
                zipOutStream.Write(target, 0, target.Length);

                compressed = new byte[memoryStream.Length];
                memoryStream.Position = 0;
                memoryStream.Read(compressed, 0, (Int32)memoryStream.Length);
                File.WriteAllBytes(outFilename, compressed);
            }
            else
            {
                File.WriteAllBytes(outFilename, target);
            }

            stream.Close();
            stream.Dispose();
        }
        public static int Deflate(byte[] inBuffer, ref byte[] outBuffer)
        {
            int newLen = 0, flagOffset = 1;

            outBuffer[0] = inBuffer[0];
            if (inBuffer[0] == 0)
            {
                flagOffset = 2;
                outBuffer[1] = inBuffer[1];
            }

            if (inBuffer.Length > 30)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, false);
                    using (DeflaterOutputStream outStream = new DeflaterOutputStream(ms, deflater))
                    {
                        outStream.IsStreamOwner = false;
                        outStream.Write(inBuffer, flagOffset, inBuffer.Length - flagOffset);
                        outStream.Flush();
                        outStream.Finish();
                    }

                    ms.Position = 0;
                    ms.Read(outBuffer, flagOffset + 1, (int)ms.Length);
                    newLen = (int)ms.Length + flagOffset + 1;
                    outBuffer[flagOffset] = 0x5a;
                }
            }
            else
            {
                Buffer.BlockCopy(inBuffer, flagOffset, outBuffer, flagOffset + 1, inBuffer.Length - flagOffset);
                outBuffer[flagOffset] = 0xa5;
                newLen = inBuffer.Length + 1;
            }

            return newLen;
        }
		MemoryStream Deflate(byte[] data, int level, bool zlib)
		{
			MemoryStream memoryStream = new MemoryStream();
			
			Deflater deflater = new Deflater(level, !zlib);
			using ( DeflaterOutputStream outStream = new DeflaterOutputStream(memoryStream, deflater) )
			{
				outStream.IsStreamOwner = false;
				outStream.Write(data, 0, data.Length);
				outStream.Flush();
				outStream.Finish();
			}
			return memoryStream;
		}
Пример #15
0
        private static void WriteDataChunks()
        {
            byte[] pixels = _image.ToByteArray();

            byte[] data = new byte[_image.PixelWidth * _image.PixelHeight * 4 + _image.PixelHeight];

            int rowLength = _image.PixelWidth * 4 + 1;

            for (int y = 0; y < _image.PixelHeight; y++)
            {
                byte compression = 0;
                if (y > 0)
                {
                    compression = 2;
                }
                data[y * rowLength] = compression;

                for (int x = 0; x < _image.PixelWidth; x++)
                {
                    // Calculate the offset for the new array.
                    int dataOffset = y * rowLength + x * 4 + 1;

                    // Calculate the offset for the original pixel array.
                    int pixelOffset = (y * _image.PixelWidth + x) * 4;

                    data[dataOffset + 0] = pixels[pixelOffset + 0];
                    data[dataOffset + 1] = pixels[pixelOffset + 1];
                    data[dataOffset + 2] = pixels[pixelOffset + 2];
                    data[dataOffset + 3] = pixels[pixelOffset + 3];

                    if (y > 0)
                    {
                        int lastOffset = ((y - 1) * _image.PixelWidth + x) * 4;

                        data[dataOffset + 0] -= pixels[lastOffset + 0];
                        data[dataOffset + 1] -= pixels[lastOffset + 1];
                        data[dataOffset + 2] -= pixels[lastOffset + 2];
                        data[dataOffset + 3] -= pixels[lastOffset + 3];
                    }
                }
            }

            byte[] buffer = null;
            int bufferLength = 0;

            MemoryStream memoryStream = null;
            try
            {
                memoryStream = new MemoryStream();

                using (DeflaterOutputStream zStream = new DeflaterOutputStream(memoryStream))
                {
                    zStream.Write(data, 0, data.Length);
                    zStream.Flush();
                    zStream.Finish();

                    bufferLength = (int)memoryStream.Length;
                    buffer = memoryStream.GetBuffer();
                }
            }
            finally
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                }
            }

            int numChunks = bufferLength / MaxBlockSize;

            if (bufferLength % MaxBlockSize != 0)
            {
                numChunks++;
            }

            for (int i = 0; i < numChunks; i++)
            {
                int length = bufferLength - i * MaxBlockSize;

                if (length > MaxBlockSize)
                {
                    length = MaxBlockSize;
                }

                WriteChunk(PngChunkTypes.Data, buffer, i * MaxBlockSize, length);
            }
        }
Пример #16
0
        private static byte[] getOutputByCompress(byte[] toByteArray) {
            int unCompressedLength = 0;
            int compressedLength = 0;

            byte[] input = toByteArray;
            unCompressedLength = input.Length;

            MemoryStream memoryStream = new MemoryStream();
            Deflater compressor = new Deflater();
            DeflaterOutputStream defos = new DeflaterOutputStream(memoryStream, compressor);
            defos.Write(input, 0, input.Length);
            defos.Flush();
            defos.Finish();
            byte[] output = memoryStream.ToArray();
            compressedLength = output.Length;

            memoryStream.Close();
            defos.Close();

            //set compress flag and compressedLength, unCompressedLength
            byte[] sendData = new byte[output.Length + TransferUtil.getLengthOfByte() + TransferUtil.getLengthOfInt() + TransferUtil.getLengthOfInt()];
            sendData[0] = TransferObject.COMPRESS_FLAG; //0:normal; 1:compress
            TransferOutputStream fos = new TransferOutputStream(sendData);
            fos.skipAByte();
            fos.writeInt(unCompressedLength);
            fos.writeInt(compressedLength);
            Array.Copy(output, 0, sendData, TransferUtil.getLengthOfByte() + TransferUtil.getLengthOfInt() + TransferUtil.getLengthOfInt(), output.Length);

            return sendData;
        }
Пример #17
0
        public static void Serialize(Stream stream, PiaFile piaFile)
        {
            if (stream == null)
                throw new ArgumentNullException("Stream");

            if (piaFile == null)
                throw new ArgumentNullException("PiaFile");

            try
            {
                // Header
                var headerString = piaFile.Header.ToString();
                var headerBytes = Encoding.Default.GetBytes(headerString);
                stream.Write(headerBytes, 0, headerBytes.Length);

                // Nodes
                var nodeString = _serializeNode(piaFile);
                var nodeBytes = Encoding.Default.GetBytes(nodeString);

                // Deflation
                byte[] deflatedBytes;
                var deflater = new Deflater(Deflater.DEFAULT_COMPRESSION);
                using (var ms = new MemoryStream())
                {
                    var deflateStream = new DeflaterOutputStream(ms, deflater);
                    deflateStream.Write(nodeBytes, 0, nodeBytes.Length);
                    deflateStream.Finish();

                    deflatedBytes = ms.ToArray();
                }

                // Checksum
                var checkSum = new byte[12];
                BitConverter.GetBytes(deflater.Adler).CopyTo(checkSum, 0); // Adler
                BitConverter.GetBytes(nodeBytes.Length).CopyTo(checkSum, 4); // InflatedSize
                BitConverter.GetBytes(deflatedBytes.Length).CopyTo(checkSum, 8); // DeflatedSize
                stream.Write(checkSum, 0, checkSum.Length);

                // Final write
                stream.Write(deflatedBytes, 0, deflatedBytes.Length);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #18
0
 public void ZipBlob()
 {
     MemoryStream sourceStream = new MemoryStream(new byte[] { 12, 34, 56, 78 });
     MemoryStream compressedStream = new MemoryStream();
     DeflaterOutputStream deflaterStream = new DeflaterOutputStream(compressedStream);
     StreamUtils.Copy(sourceStream, deflaterStream, new byte[4096]);
     deflaterStream.Finish();
     compressedStream.Capacity = (int) compressedStream.Length;
     StructInstance instance = PrepareInstance(
         "struct A { blob q [len=FileSize, encoding=zlib]; }",
         compressedStream.GetBuffer());
     BlobCell cell = (BlobCell) instance.Cells[0];
     Assert.AreEqual(4, cell.DataStream.Length);
 }
Пример #19
0
        /// <summary>
        /// see <see cref="SwfDotNet.IO.Tags.BaseTag">base class</see>
        /// </summary>
        public override void UpdateData(byte version)
        {
            if (version < 2)
                return;

            // Compression process
            int lenghtOfCompressedBlock = 0;
            byte[] compressArray = null;
            MemoryStream unCompressedStream = new MemoryStream();
            BufferedBinaryWriter unCompressedWriter = new BufferedBinaryWriter(unCompressedStream);

            if (this._bitmapFormat == 3)
            {
                this._colorMapData.WriteTo(unCompressedWriter);
            }
            else if (this._bitmapFormat == 4 || this._bitmapFormat == 5)
            {
                this._bitmapColorData.WriteTo(unCompressedWriter);
            }

            MemoryStream compressedStream = new MemoryStream();
            DeflaterOutputStream ouput = new DeflaterOutputStream(compressedStream);
            byte[] unCompressArray = unCompressedStream.ToArray();
            ouput.Write(unCompressArray, 0, unCompressArray.Length);
            ouput.Finish();
            compressArray = compressedStream.ToArray();
            lenghtOfCompressedBlock = compressArray.Length;
            ouput.Close();
            unCompressedStream.Close();

            //Writing process
            MemoryStream m = new MemoryStream();
            BufferedBinaryWriter w = new BufferedBinaryWriter(m);

            RecordHeader rh = new RecordHeader(TagCode, GetSizeOf(lenghtOfCompressedBlock));

            rh.WriteTo(w);
            w.Write(this._characterId);
            w.Write(this._bitmapFormat);
            w.Write(this._bitmapWidth);
            w.Write(this._bitmapHeight);

            if (this._bitmapFormat == 3)
            {
                w.Write(this._bitmapColorTableSize);
                w.Write(compressArray);
            }
            else if (this._bitmapFormat == 4 || this._bitmapFormat == 5)
            {
                w.Write(compressArray);
            }

            w.Flush();
            // write to data array
            _data = m.ToArray();
        }
Пример #20
0
        /// <summary>
        /// Compression through zlib
        /// </summary>
        public CString ZCompress()
        {
            // Do Compression
            try
            {
                MemoryStream MemStream = new MemoryStream();
                DeflaterOutputStream DefStream = new DeflaterOutputStream(MemStream, new Deflater(Deflater.DEFAULT_COMPRESSION, false));
                DefStream.Write(mBuffer.ToArray(), 0, mBuffer.Count);
                DefStream.Finish();
                DefStream.Close();

                // Recreate Buffer
                mBuffer = MemStream.ToArray().ToList();

            }
            catch (Exception e)
            {
            }

            return this;
        }