This filter stream is used to decompress a "GZIP" format stream. The "GZIP" format is described baseInputStream RFC 1952. author of the original java version : John Leuner
Inheritance: ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream
コード例 #1
3
        public byte[] Decompress(byte[] data)
        {
            using (MemoryStream inputStream = new MemoryStream())
            {
                inputStream.Write(data, 0, data.Length);
                inputStream.Position = 0;

                using (Stream decompressStream = new GZipInputStream(inputStream))
                {
                    using (MemoryStream outputStream = new MemoryStream())
                    {
                        byte[] buffer = new byte[BUFFER_SIZE];
                        while (true)
                        {
                            int size = decompressStream.Read(buffer, 0, buffer.Length);
                            if (size > 0)
                            {
                                outputStream.Write(buffer, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        decompressStream.Close();
                        return outputStream.ToArray();
                    }
                }
            }
        }
コード例 #2
1
ファイル: Data.cs プロジェクト: PokeD/TMXParserPCL
        private Stream Decode()
        {
            Stream stream;

            if (Encoding != "base64")
                throw new Exception("TmxMapperPCL.Data: Only Base64-encoded data is supported.");

            var rawData = Convert.FromBase64String(Value);
            var memStream = new MemoryStream(rawData);

            if (Compression == "gzip")
                stream = new GZipInputStream(memStream);
            else if (Compression == "zlib")
                stream = new InflaterInputStream(memStream);
            else if (Compression != null)
                throw new Exception("TmxMapperPCL.Data: Unknown compression.");
            else
                stream = memStream;

            var outputStream = new MemoryStream();
            stream.CopyTo(outputStream);
            stream = outputStream;

            return stream;
        }
コード例 #3
0
ファイル: ArchiveManager.cs プロジェクト: hexandr/uLearn
		/// <summary>
		/// Extracts contents of GZipped Tar file to specified directory
		/// </summary>
		/// <param name="filename">Input .tar.gz file</param>
		/// <param name="directory">Output directory</param>
		public static void ExtractTar(string filename, string directory)
		{
			using (Stream inStream = File.OpenRead(filename))
			using (Stream gzipStream = new GZipInputStream(inStream))
			using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream))
				tarArchive.ExtractContents(directory);
		}
コード例 #4
0
ファイル: GUnzip.cs プロジェクト: RoastBoy/nant
        /// <summary>
        /// Extracts the file from the gzip archive.
        /// </summary>
        protected override void ExecuteTask() {
            try {
                using (GZipInputStream gzs = new GZipInputStream(SrcFile.OpenRead())) {
                    Log(Level.Info, "Expanding '{0}' to '{1}' ({2} bytes).", 
                        SrcFile.FullName, DestFile.FullName, gzs.Length);

                    // holds data from src file
                    byte[] data = new byte[8 * 1024];

                    // first read from input to ensure we're dealing with valid
                    // src file before we actually create the dest file
                    int size = gzs.Read(data, 0, data.Length);

                    // write expanded data to dest file
                    using (FileStream fs = new FileStream(DestFile.FullName, FileMode.Create, FileAccess.Write, FileShare.None)) {
                        while (size > 0) {
                            fs.Write(data, 0, size);
                            size = gzs.Read(data, 0, data.Length);
                        }
                        // close output stream
                        fs.Close();
                    }
                    // close input stream
                    gzs.Close();
                }
            } catch (IOException ex) {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                    "Failed to expand '{0}' to '{1}'.", SrcFile.FullName, 
                    DestFile.FullName), Location, ex);
            } catch (GZipException ex) {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                    "Invalid gzip file '{0}'.", SrcFile.FullName), Location, ex);
            }
        }
コード例 #5
0
ファイル: GZipFldField.cs プロジェクト: puring0815/OpenKore
	/**
	 * Construct a new GZipFldField object and load a field file
	 * from the specified filename.
	 *
	 * @throws IOException, InvalidFieldException, ApplicationException
	 */
	public GZipFldField(string filename) {
		Stream file = new FileStream(filename, FileMode.Open);
		Stream gzipStream = new GZipInputStream(file);
		field = new FldField(gzipStream);
		gzipStream.Close();
		file.Close();
	}
コード例 #6
0
ファイル: Resources.cs プロジェクト: Glain/FFTPatcher
        static Resources()
        {
            using ( MemoryStream memStream = new MemoryStream( FFTPatcher.TextEditor.Properties.Resources.Resources_tar, false ) )
            using ( GZipInputStream gzStream = new GZipInputStream( memStream ) )
            using ( TarInputStream tarStream = new TarInputStream( gzStream ) )
            {
                TarEntry entry;
                entry = tarStream.GetNextEntry();
                while ( entry != null )
                {
                    if ( entry.Size != 0 && !string.IsNullOrEmpty( entry.Name ) )
                    {
                        if (entry.Name.EndsWith( ".xml" ))
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.Load( tarStream );
                            resourceMapping[entry.Name] = doc;
                        }
                        else
                        {
                            byte[] bytes = new byte[entry.Size];
                            ICSharpCode.SharpZipLib.Core.StreamUtils.ReadFully( tarStream, bytes );
                            otherResources[entry.Name] = bytes;
                        }
                    }

                    entry = tarStream.GetNextEntry();
                }

            }
        }
コード例 #7
0
ファイル: TarGzExtracter.cs プロジェクト: GNOME/capuchin
 public void Extract(string path, string dest_dir)
 {
     GZipInputStream gzstream = new GZipInputStream(new FileStream( path, FileMode.Open));
     TarExtracter untar = new TarExtracter();
     untar.Extract(gzstream, dest_dir);
     gzstream.Close();
 }
コード例 #8
0
ファイル: UudecodedUnGZipper.cs プロジェクト: 1pindsvin/yagni
 private static byte[] Decompress(byte[] compressed)
 {
     using (var compressedMemoryStream = new MemoryStream(compressed))
     {
         var gZipInputStream = new GZipInputStream(compressedMemoryStream);
         try
         {
             using (var unCompressedStream = new MemoryStream())
             {
                 var noOfBytesReadTotal = 0;
                 const int blockSize = 2048;
                 var byteBlock = new byte[blockSize];
                 while (true)
                 {
                     var noOfBytesRead = gZipInputStream.Read(byteBlock, 0, byteBlock.Length);
                     if (noOfBytesRead <= 0)
                     {
                         break;
                     }
                     noOfBytesReadTotal += noOfBytesRead;
                     unCompressedStream.Write(byteBlock, 0, noOfBytesRead);
                 }
                 var decompressedWithoutTrailingZeros =
                     unCompressedStream.GetBuffer().Take(noOfBytesReadTotal);
                 return decompressedWithoutTrailingZeros.ToArray();
             }
         }
         finally
         {
             gZipInputStream.Close();
         }
     }
 }
コード例 #9
0
        // select the right decompression stream
        public override Stream GetResponseStream()
        {
            try
            {
                Stream responseStream = _response.GetResponseStream();
                Stream compressedStream = null;
                if (_response.ContentEncoding == "gzip")
                {
                    compressedStream = new
                      GZipInputStream(responseStream);
                }
                else if (_response.ContentEncoding == "deflate")
                {
                    compressedStream = new
                      ZipInputStream(responseStream);
                }

                if (compressedStream == null)
                    compressedStream = responseStream;

                if (compressedStream != null)
                {
                    // Decompress
                    MemoryStream decompressedStream = new MemoryStream();
                    int totalSize = 0;
                    int size = 2048;
                    byte[] writeData = new byte[2048];
                    while (true)
                    {
                        size = compressedStream.Read(writeData, 0, size);
                        totalSize += size;
                        if (size > 0)
                            decompressedStream.Write(writeData, 0, size);
                        else
                            break;
                    }

                    if (compressedStream != responseStream)
                        responseStream.Close();
                    compressedStream.Close();

                    decompressedStream.Seek(0, SeekOrigin.Begin);

                    using (MemoryStream logstream = new MemoryStream(decompressedStream.GetBuffer()))
                    using (StreamReader sr = new StreamReader(logstream))
                    {
                        DebugHelper.WriteLogEntry("ResponseStream: " + sr.ReadToEnd());
                    }

                    decompressedStream.Seek(0, SeekOrigin.Begin);
                    return decompressedStream;
                }
                return compressedStream;
            }
            catch (Exception ex)
            {
                DebugHelper.WriteLogEntry(ex, "GZIP error");
                return null;
            }
        }
コード例 #10
0
        public void TestMigration()
        {
            string dir = Path.Combine (Path.GetTempPath (), Path.GetRandomFileName ());
            Directory.CreateDirectory (dir);

            var assembly = Assembly.GetExecutingAssembly ();
            using (Stream fs = assembly.GetManifestResourceStream ("longomatch.tar.gz")) {
                using (Stream gzipStream = new GZipInputStream (fs)) {
                    using (TarArchive tarArchive = TarArchive.CreateInputTarArchive (gzipStream)) {
                        tarArchive.ExtractContents (dir);
                    }
                }
            }

            CouchbaseStorageLongoMatch storage = new CouchbaseStorageLongoMatch (dir, "longomatch");
            Assert.AreEqual (2, storage.RetrieveAll<SportsTeam> ().Count ());
            Assert.AreEqual (1, storage.RetrieveAll<DashboardLongoMatch> ().Count ());
            Assert.AreEqual (1, storage.RetrieveAll<ProjectLongoMatch> ().Count ());

            SportsTeam team = storage.RetrieveAll<SportsTeam> ().First ();
            Assert.DoesNotThrow (team.Load);

            DashboardLongoMatch dashboard = storage.RetrieveAll<DashboardLongoMatch> ().First ();
            Assert.DoesNotThrow (dashboard.Load);

            ProjectLongoMatch project = storage.RetrieveAll<ProjectLongoMatch> ().First ();
            Assert.DoesNotThrow (project.Load);
        }
コード例 #11
0
ファイル: GZipTests.cs プロジェクト: foresightbrand/brandqq
        public void TestGZip()
        {
            MemoryStream ms = new MemoryStream();
            GZipOutputStream outStream = new GZipOutputStream(ms);

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

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

            ms.Seek(0, SeekOrigin.Begin);

            GZipInputStream inStream = new GZipInputStream(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]);
            }
        }
コード例 #12
0
        public static byte[] GetDecompressedBytes(this WWW www)
        {
            #if UNITY_STANDALONE_WIN || UNITY_WEBGL
            string contentEncoding;
            if (www.responseHeaders == null ||
                !www.responseHeaders.TryGetValue(ContentEncodingHeaderName, out contentEncoding) ||
                !contentEncoding.Equals(GzipContentEncodingValue, StringComparison.OrdinalIgnoreCase))
            {
                return www.bytes;
            }

            byte[] buffer = new byte[4096];
            using (var stream = new MemoryStream(www.bytes))
            using (var gzip = new GZipInputStream(stream))
            using (var outMs = new MemoryStream(www.bytes.Length))
            {
                int bytesRead = 0;
                while ((bytesRead = gzip.Read(buffer, 0, buffer.Length)) > 0)
                {
                    outMs.Write(buffer,0, bytesRead);
                }
                return outMs.ToArray();
            }

            #else
            return www.bytes;
            #endif
        }
コード例 #13
0
ファイル: GZipTests.cs プロジェクト: jeske/StepsDB-alpha
        public void BigStream()
        {
            window_ = new WindowedStream(0x3ffff);
            outStream_ = new GZipOutputStream(window_);
            inStream_ = new GZipInputStream(window_);

            long target = 0x10000000;
            readTarget_ = writeTarget_ = target;

            Thread reader = new Thread(Reader);
            reader.Name = "Reader";
            reader.Start();

            Thread writer = new Thread(Writer);
            writer.Name = "Writer";

            DateTime startTime = DateTime.Now;
            writer.Start();

            writer.Join();
            reader.Join();

            DateTime endTime = DateTime.Now;

            TimeSpan span = endTime - startTime;
            Console.WriteLine("Time {0}  processes {1} KB/Sec", span, (target / 1024) / span.TotalSeconds);
        }
コード例 #14
0
		public void TestGZip()
		{
			MemoryStream ms = new MemoryStream();
			GZipOutputStream outStream = new GZipOutputStream(ms);

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

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

			ms.Seek(0, SeekOrigin.Begin);

			GZipInputStream inStream = new GZipInputStream(ms);
			byte[] buf2 = new byte[buf.Length];
			int currentIndex = 0;
			int count = buf2.Length;
			
			while (true) {
				int numRead = inStream.Read(buf2, currentIndex, count);
				if (numRead <= 0) {
					break;
				}
				currentIndex += numRead;
				count -= numRead;
			}

			Assert.AreEqual(0, count);
			
			for (int i = 0; i < buf.Length; ++i) {
				Assert.AreEqual(buf2[i], buf[i]);
			}
		}
コード例 #15
0
        public void GZip_Compress_Extract_Test() {
            var plainStream = PlainText.ToStream();
            plainStream.Seek(0, SeekOrigin.Begin);

            var plainData = Encoding.UTF8.GetBytes(PlainText);
            byte[] compressedData;
            byte[] extractedData;

            // Compress
            using(var compressedStream = new MemoryStream())
            using(var gzs = new GZipOutputStream(compressedStream)) {
                gzs.SetLevel(5);
                gzs.Write(plainData, 0, plainData.Length);
                gzs.Finish();
                compressedData = compressedStream.ToArray();
            }

            Assert.IsNotNull(compressedData);

            // Extract
            using(var compressedStream = new MemoryStream(compressedData)) {
                // compressedStream.Seek(0, SeekOrigin.Begin);
                using(var gzs = new GZipInputStream(compressedStream))
                using(var extractedStream = new MemoryStream()) {
                    StreamTool.CopyStreamToStream(gzs, extractedStream);
                    extractedData = extractedStream.ToArray();
                }
            }

            Assert.IsNotNull(extractedData);
            string extractedText = Encoding.UTF8.GetString(extractedData).TrimEnd('\0');

            Assert.AreEqual(PlainText, extractedText);
        }
コード例 #16
0
        public string Decompress(string filename)
        {
            StringBuilder result = null;

            try
            {
                Stream s = new GZipInputStream(File.OpenRead(filename));

                result = new StringBuilder(8192);
                UTF7Encoding encoding = new UTF7Encoding(true);

                int size = 2048;
                byte[] writeData = new byte[2048];
                while (true)
                {
                    size = s.Read(writeData, 0, size);
                    if (size > 0)
                    {
                       result.Append(encoding.GetString(writeData,0,size));
                    }
                    else
                    {
                        break;
                    }
                }
                s.Close();

            } // end try
            catch (GZipException)
            {
                throw new Exception("Error: The file being read contains invalid data.");
            }
            catch (FileNotFoundException)
            {
                throw new Exception("Error:The file specified was not found.");
            }
            catch (ArgumentException)
            {
                throw new Exception("Error: path is a zero-length string, contains only white space, or contains one or more invalid characters");
            }
            catch (PathTooLongException)
            {
                throw new Exception("Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.");
            }
            catch (DirectoryNotFoundException)
            {
                throw new Exception("Error: The specified path is invalid, such as being on an unmapped drive.");
            }
            catch (IOException)
            {
                throw new Exception("Error: An I/O error occurred while opening the file.");
            }
            catch (UnauthorizedAccessException)
            {
                throw new Exception("Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions.");
            }

            return result.ToString();
        }
コード例 #17
0
ファイル: WebServer.cs プロジェクト: patel22p/dorumon
    private static byte[] Unpack(byte[] _bytes)
    {
        ICSharpCode.SharpZipLib.GZip.GZipInputStream _GZipStream = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(new MemoryStream(_bytes));
        byte[] _buffer2 = new byte[99999];
        int    count    = _GZipStream.Read(_buffer2, 0, _buffer2.Length);

        return(Substr(_buffer2, count));
    }
コード例 #18
0
 public static void Untgz(Stream stream, string outDirPath)
 {
     using (var inputStream = new GZipInputStream(stream)) {
         var archive = TarArchive.CreateInputTarArchive(inputStream);
         archive.AsciiTranslate = false;
         archive.ExtractContents(outDirPath);
     }
 }
コード例 #19
0
 internal static void Extract(string filename)
 {
     using (Stream s = new GZipInputStream(File.OpenRead(filename)))
     using (FileStream fs = File.Create(filename + ".work"))
     {
         StreamUtils.Copy(s, fs, new byte[4096]);
     }
 }
コード例 #20
0
 public WikiContent Import(string filename, Stream stream)
 {
     _Log.Debug("Loading from {0}", FormatExtension);
     filename = Path.GetFileNameWithoutExtension(filename);
     using (var gzip = new GZipInputStream(stream))
     {
         return WikiImporter.ImportFrom(filename, gzip, this);
     }
 }
コード例 #21
0
 public static void Untgz(string inPath, string outDirPath)
 {
     using (var fs = File.OpenRead(inPath)) {
         using (var stream = new GZipInputStream(fs)) {
             var archive = TarArchive.CreateInputTarArchive(stream);
             archive.ExtractContents(outDirPath);
         }
     }
 }
コード例 #22
0
 public static object Deserialize(byte[] data)
 {
     MemoryStream ms = new MemoryStream(data);
     using (GZipInputStream stm = new GZipInputStream(ms))
     {
         BinaryFormatter bf = new BinaryFormatter(new RemotingSurrogateSelector(), new StreamingContext(StreamingContextStates.Persistence));
         return bf.Deserialize(stm);
     }
 }
コード例 #23
0
ファイル: GZipHelper.cs プロジェクト: s7loves/mypowerscgl
 public static string UnCompress(string gzipFile) {
     byte[] dataBuffer = new byte[4096];
     string destFile =Path.GetDirectoryName(gzipFile)+"\\"+ Path.GetFileNameWithoutExtension(gzipFile);
     using (GZipInputStream gs = new GZipInputStream(File.OpenRead(gzipFile))) {
         using (FileStream fs = File.Create(destFile)) {
             StreamUtils.Copy(gs, fs, dataBuffer);
         }
     }
     return destFile;
 }
コード例 #24
0
ファイル: Compression.cs プロジェクト: intelliBrain/Lean
 /// <summary>
 /// Extract tar.gz files to disk
 /// </summary>
 /// <param name="source">Tar.gz source file</param>
 /// <param name="destination">Location folder to unzip to</param>
 public static void UnTarGzFiles(string source, string destination)
 {
     var inStream = File.OpenRead(source);
     var gzipStream = new GZipInputStream(inStream);
     var tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
     tarArchive.ExtractContents(destination);
     tarArchive.Close();
     gzipStream.Close();
     inStream.Close();
 }
コード例 #25
0
ファイル: ArcFileSystem.cs プロジェクト: JokieW/ShiningHill
        public ArcFileSystem()
        {
            data = new byte[90016];

            GZipInputStream gzipStream = new GZipInputStream(new FileStream("Assets/SilentHill3/Archives/arc.arc", FileMode.Open, FileAccess.Read));

            gzipStream.Read(data, 0, 90016);

            ReadAll();
        }
コード例 #26
0
ファイル: RotatedLog.cs プロジェクト: demonix/KeClientTracer
 private static string ComputeHashFromGz(string filename)
 {
     string newHash;
     using (GZipInputStream logFileStream = new GZipInputStream(File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
     {
         byte[] headBytes = new byte[BytesToRead];
         logFileStream.Read(headBytes, 0, BytesToRead);
         SHA1 sha1 = SHA1.Create();
         newHash = BitConverter.ToString(sha1.ComputeHash(headBytes));
     }
     return newHash;
 }
コード例 #27
0
ファイル: ArchiveService.cs プロジェクト: keep3r/Sonarr
        private void ExtractTgz(string compressedFile, string destination)
        {
            Stream inStream = File.OpenRead(compressedFile);
            Stream gzipStream = new GZipInputStream(inStream);

            TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
            tarArchive.ExtractContents(destination);
            tarArchive.Close();

            gzipStream.Close();
            inStream.Close();
        }
コード例 #28
0
ファイル: FileExtractor.cs プロジェクト: ADTC/VietOCR
        public static void ExtractTGZ(String gzArchiveName, String destFolder)
        {
            Stream inStream = File.OpenRead(gzArchiveName);
            Stream gzipStream = new GZipInputStream(inStream);

            TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
            tarArchive.ExtractContents(destFolder);
            tarArchive.Close();

            gzipStream.Close();
            inStream.Close();
        }
コード例 #29
0
ファイル: GeoIP.cs プロジェクト: CH4Code/OpenRA
 public static void Initialize()
 {
     try
     {
         using (var fileStream = new FileStream("GeoLite2-Country.mmdb.gz", FileMode.Open, FileAccess.Read))
             using (var gzipStream = new GZipInputStream(fileStream))
                 database = new DatabaseReader(gzipStream);
     }
     catch (Exception e)
     {
         Log.Write("geoip", "DatabaseReader failed: {0}", e);
     }
 }
コード例 #30
0
 /// <summary>
 /// Extracts data from a .zip archive.
 /// </summary>
 /// <param name="targetDir">The directory to put the extracted data in.</param>
 /// <param name="zipFile">The file to extract data from.</param>
 public static void UnzipFile(string targetDir, string zipFile)
 {
     using (Stream inStream = File.OpenRead(zipFile))
     {
         using (Stream gzipStream = new GZipInputStream(inStream))
         {
             using (TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream))
             {
                 tarArchive.ExtractContents(targetDir);
             }
         }
     }
 }
コード例 #31
0
        private static void Main(string[] args)
        {
            Console.WriteLine("LegendaryClient Updater");
            Stream inStream = File.OpenRead(Path.Combine("temp", "1.0.1.2.zip"));

            using (GZipInputStream gzipStream = new GZipInputStream(inStream))
            {
                TarArchive tarArchive = TarArchive.CreateInputTarArchive(gzipStream);
                tarArchive.ExtractContents("temp");
                tarArchive.CloseArchive();
            }
            System.Diagnostics.Process.Start("LegendaryClient.exe");
            Environment.Exit(0);
        }
コード例 #32
0
        public void TestSharpZlib()
        {
            compressor = new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(compressed)
            {
                IsStreamOwner = false
            };
            StartCompression();
            compressor.Write(input.GetBuffer(), 0, inputSize);
            compressor.Close();

            EndCompression();

            var decompressor = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(compressed);

            decompressor.CopyTo(decompressed);

            AfterDecompression();
        }
コード例 #33
0
ファイル: TarGzipArchive.cs プロジェクト: Terradue/Stars
        protected override BlockingStream GetTarStream(IAsset asset)
        {
            const int      chunk          = 4096;
            BlockingStream blockingStream = new BlockingStream(1000);

            asset.GetStreamable().GetStreamAsync()
            .ContinueWith(task =>
            {
                var stream = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(task.GetAwaiter().GetResult());
                Task.Factory.StartNew(() =>
                {
                    int read;
                    var buffer = new byte[chunk];
                    do
                    {
                        read = stream.Read(buffer, 0, chunk);
                        blockingStream.Write(buffer, 0, read);
                    } while (read == chunk);
                    blockingStream.Close();
                });
            });
            return(blockingStream);
        }
コード例 #34
0
        static void Func(string path, bool convertTransparent)
        {
            var InvalidChars = Path.GetInvalidPathChars();

            foreach (char invalid in InvalidChars)
            {
                path = path.Replace(invalid.ToString(), "");
            }

            //This block is to give a little extra compatibility
            //for older Shiny games and extracted .cha files
            try
            {
                //Unpack the GZip file
                MemoryStream compressedStream   = new MemoryStream(File.ReadAllBytes(path));
                MemoryStream uncompressedStream = new MemoryStream();
                ICSharpCode.SharpZipLib.GZip.GZipInputStream GZipOut = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(compressedStream);
                GZipOut.CopyTo(uncompressedStream);
                compressedStream.Close();
                GZipOut.Close();

                //This is the extracted file from the GZip buffer.
                //Otherwise known as the Eversion character file.
                outStreamArray = uncompressedStream.ToArray();

                //Clear the streams and dispose of them.
                uncompressedStream.Close();
                compressedStream.Close();
            }
            catch
            {
                outStreamArray = File.ReadAllBytes(path);
            }

            //This is the header of the Shiny character archive.
            byte[] header = new byte[0x40];
            Array.Copy(outStreamArray, header, 0x40);

            //Grab the width, height, of the sprites from the header
            byte[] SpriteWidthBytes  = new byte[2];
            byte[] SpriteHeightBytes = new byte[2];
            Array.Copy(header, 0x4, SpriteWidthBytes, 0, 2);

            //This is the rest of the Shiny character archive, minus the header.
            byte[] SpriteBuffer = new byte[outStreamArray.Length - header.Length];
            Array.Copy(outStreamArray, header.Length, SpriteBuffer, 0, outStreamArray.Length - header.Length);

            //This is the visual XY and collision XY offset for the sprite.
            //It's not used here, since we only care about the sprite data.
            //So instead we only care about its length.
            int SpriteDataHeaderLength = 0;

            //The transparency colour of sprites are
            //defined in character sprites but not background sprites
            byte[] SpriteTransparentColour = new byte[3];

            if (extension == ".cha")
            {
                SpriteDataHeaderLength = 0x10;
                Array.Copy(header, 0x24, SpriteTransparentColour, 0, 3);
                Array.Copy(header, 0x6, SpriteHeightBytes, 0, 2);
            }

            if (extension == ".zrs")
            {
                SpriteTransparentColour = new byte[3] {
                    0x40, 0, 0x40
                };
                Array.Copy(header, 0x8, SpriteHeightBytes, 0, 2);
            }

            //Initialise width and height to value
            if (!BitConverter.IsLittleEndian)
            {
                Array.Reverse(SpriteWidthBytes);
                Array.Reverse(SpriteHeightBytes);
            }
            ushort SpriteWidth  = BitConverter.ToUInt16(SpriteWidthBytes, 0);
            ushort SpriteHeight = BitConverter.ToUInt16(SpriteHeightBytes, 0);

            //Some helpful stuff for the loop bounds
            int  SpriteRegionLength = SpriteWidth * SpriteHeight * 3;
            bool IsPaletted         = false;

            byte[] PaletteBytes = new byte[256 * 4];
            if (SpriteRegionLength > SpriteBuffer.Length)
            {
                IsPaletted          = true;
                SpriteRegionLength /= 3;
                Array.Copy(SpriteBuffer, PaletteBytes, PaletteBytes.Length);
                var temp = new byte[SpriteRegionLength];
                Array.Copy(SpriteBuffer, PaletteBytes.Length, temp, 0, SpriteRegionLength);
                SpriteBuffer = temp;
            }

            int SpriteCount = SpriteBuffer.Length / (SpriteRegionLength + SpriteDataHeaderLength);

            for (int i = 0; i < SpriteCount; i++)
            {
                //This is the buffer of the actual sprite we want to rip.
                var    separatoroffset = i * SpriteDataHeaderLength + SpriteDataHeaderLength;
                var    completeoffset  = separatoroffset + i * SpriteRegionLength;
                byte[] sprite          = new byte[SpriteRegionLength];
                Array.Copy(SpriteBuffer, completeoffset, sprite, 0, SpriteRegionLength);

                int ColourBufferLength = IsPaletted
                    ? PaletteBytes.Length
                    : sprite.Length;

                //Create the image from the bytes
                //We start by converting the bytes into a colour proper
                List <Color> Colours = new List <Color>();
                for (int j = 0; j < ColourBufferLength; j += 3)
                {
                    Color TransparentColour = Color.FromArgb(SpriteTransparentColour[0], SpriteTransparentColour[1], SpriteTransparentColour[2]);
                    Color PixelColour       = IsPaletted
                        ? Color.FromArgb((int)PaletteBytes[j], (int)PaletteBytes[j + 1], (int)PaletteBytes[j + 2])
                        : Color.FromArgb((int)sprite[j], (int)sprite[j + 1], (int)sprite[j + 2]);
                    if (convertTransparent && PixelColour == TransparentColour)
                    {
                        PixelColour = Color.FromArgb(0, PixelColour.R, PixelColour.G, PixelColour.B);
                    }
                    Colours.Add(PixelColour);
                    if (IsPaletted)
                    {
                        j++;
                    }
                }

                //Now we draw the image !!
                var OutImage = new Bitmap(SpriteWidth, SpriteHeight);

                for (int k = 0; k < SpriteWidth * SpriteHeight; k++)
                {
                    int x         = k % SpriteWidth;
                    int y         = k / SpriteWidth;
                    var WriteThis = IsPaletted
                        ? Colours[SpriteBuffer[k]]
                        : Colours[k];

                    OutImage.SetPixel(x, y, WriteThis);
                }

                var graphic = Graphics.FromImage(OutImage);

                //A few tidbits to drop the files in a folder next to where they came from.
                var filename  = Path.GetFileNameWithoutExtension(path);
                var file      = Path.GetFileName(path);
                var directory = path.Replace(file, "");
                if (i == 0 && (File.Exists(directory + filename) || Directory.Exists(directory + filename)))
                {
                    ShinyTools.Helpers.Console.WriteColor("ERROR: Could not create the directory or file as it already exists.\nPlease remove the file and try again.\n", ConsoleColor.Red);
                    Console.WriteLine("Press any key to quit the application.");
                    Console.ReadKey(true);
                    ShinyTools.Helpers.Application.Quit(QuitResult, 100, 80);
                }
                else
                {
                    Directory.CreateDirectory(directory + filename);
                    OutImage.Save($"{directory+filename}{Path.DirectorySeparatorChar}{filename}_{i.ToString().PadLeft(SpriteCount.ToString().Length, '0')}.png", System.Drawing.Imaging.ImageFormat.Png);
                }
            }
            QuitResult = "OK!";
            ShinyTools.Helpers.Application.Quit(QuitResult, 1200);
        }