private IEnumerator WriteTex(RenderTexture rt, bool alpha) { //Pull texture off of GPU var req = AsyncGPUReadback.Request(rt, 0, 0, rt.width, 0, rt.height, 0, 1, alpha ? TextureFormat.RGBA32 : TextureFormat.RGBAFloat); while (!req.done) { yield return(null); } RenderTexture.ReleaseTemporary(rt); string path = GetCaptureFilename(); LogScreenshotMessage("Writing rendered screenshot to " + path.Substring(Paths.GameRootPath.Length)); //Write raw pixel data to a file //Uses pngcs Unity fork: https://github.com/andrew-raphael-lukasik/pngcs if (alpha) { using (var buffer = req.GetData <Color32>()) yield return(PNG.WriteAsync(buffer.ToArray(), req.width, req.height, 8, true, false, path)); } else { using (var buffer = req.GetData <Color>()) yield return(PNG.WriteAsync(buffer.ToArray(), req.width, req.height, 8, false, false, path)); } }
public static Type GetImageFileTypeFromSignature(byte[] buffer) { if (TEXN.IsValid(buffer)) { return(typeof(TEXN)); } if (PVRT.IsValid(buffer)) { return(typeof(PVRT)); } if (DDS.IsValid(buffer)) { return(typeof(DDS)); } if (BMP.IsValid(buffer)) { return(typeof(BMP)); } if (JPEG.IsValid(buffer)) { return(typeof(JPEG)); } if (PNG.IsValid(buffer)) { return(typeof(PNG)); } return(null); }
protected override void ImprintPNG(byte[] data) { uint[] crcTable = null; uint crc = PNG.CRC32(PNG_IDAT_HEADER, 0, PNG_IDAT_HEADER.Length, 0, ref crcTable); crc = PNG.CRC32(data, 0, data.Length, crc, ref crcTable); byte[] crcb = BitConverter.GetBytes(crc); int IEND = 0; for (int i = 0; i < image.Chunks.Count; i++) { if (image.Chunks[i].Name == "IEND") { IEND = i; break; } } image.Chunks.Insert(IEND, new PNGChunk() { Name = "IDAT", Standard = true, Critical = true, CRC = crc, CRCBytes = new byte[4] { crcb[3], crcb[2], crcb[1], crcb[0] }, ValidCRC = true, Data = data }); }
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); }
public void loadFromStream(Stream stream) { size = stream.Length; if (JPEG.test(stream)) { _img = new JPEG(stream); type = JPEG.MIME; ((JPEG)_img).extractHeaders(); // preserve headers for later meta = ((JPEG)_img).metaInfo(); // save thumb data as Blob object thumbData; if (meta.ContainsKey("thumb") && ((Dictionary <string, object>)meta["thumb"]).TryGetValue("data", out thumbData)) { Blob blob = new Blob(new List <object> { (byte[])thumbData }, new Dictionary <string, string> { { "type", "image/jpeg" } }); Moxie.compFactory.add(blob.uid, blob); ((Dictionary <string, object>)meta["thumb"])["data"] = blob.ToObject(); } } else if (PNG.test(stream)) { _img = new PNG(stream); type = PNG.MIME; } else { Error(this, new ErrorEventArgs(ImageError.WRONG_FORMAT)); return; } Dictionary <string, int> info = _img.info(); if (info != null) { width = info["width"]; height = info["height"]; } BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); _bm = new WriteableBitmap(bitmapImage); Load(this, null); }
public static void DumpDatabase(string folder) { if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } foreach (TEXN tex in m_textures) { string textureName = "tex_" + tex.TextureID.Data.ToString("x16") + ".png"; PNG png = new PNG(tex.Texture); png.Write(folder + textureName); } }
protected override void ImprintPNG(byte[] data) { uint[] crcTable = null; uint crc = PNG.CRC32(PNG_TEXT_HEADER, 0, PNG_TEXT_HEADER.Length, 0, ref crcTable); crc = PNG.CRC32(data, 0, data.Length, crc, ref crcTable); byte[] crcb = BitConverter.GetBytes(crc); image.Chunks.Insert(1, new PNGChunk() { Name = "tEXt", Standard = false, Critical = false, CRC = crc, CRCBytes = new byte[4] { crcb[3], crcb[2], crcb[1], crcb[0] }, ValidCRC = true, Data = data }); }
public Bitmap(string file) { ReadStream stream = new ReadStream(File.ReadAllBytes(file)); string extension = Path.GetExtension(file); switch (extension.ToLower()) { case ".bmp": BMP.Decode(stream, this); break; case ".png": PNG.Decode(stream, this); break; default: Debug.Assert(false, "Image file extension not supported: {0}", extension); break; } }
public PNG GeneratePNG(Texture2D data) { var png = new PNG(); using (var stream = new MemoryStream()) { data.SaveAsPng(stream, data.Width, data.Height); png.data = stream.ToArray(); } png.ChunkLabel = "Lot Thumbnail"; png.ChunkProcessed = true; png.ChunkType = "PNG_"; png.AddedByPatch = true; return(png); }
// load JSON game definition and all files for RUN public static bool LoadData(string cartridgeName) { uRetroConfig.cartridgeName = cartridgeName; string path = GetRoot() + "/" + uRetroConfig.cartridgesFolder + "/" + uRetroConfig.cartridgeName; if (!Directory.Exists(path)) { uRetroConsole.PrintError("Cartridge folder with name '" + cartridgeName + "' missing!"); return(false); } path = GetRoot() + "/" + uRetroConfig.cartridgesFolder + "/" + uRetroConfig.cartridgeName + "/"; // CONFIG uRetroSystem.LoadRetroEngineConfig(); // COLORS Texture2D colors = PNG.LoadPNG(path + uRetroConfig.fileColors); uRetroColors.CreatePalette(colors); // SPRITES Texture2D sprites = PNG.LoadPNG(path + uRetroConfig.fileSprites); uRetroSprites.CreateSprites(sprites); // FONTS Texture2D fonts = PNG.LoadPNG(path + uRetroConfig.fileFont); uRetroText.CreateFont(fonts); // Tilemaps uRetroTilemap.Load(); // Create Display uRetroDisplay.CreateDisplay(GameObject.FindGameObjectWithTag("uRetroDisplay")); // Set Resolution uRetroDisplay.SetResolution(uRetroConfig.screen_width, uRetroConfig.screen_height, 0); uRetroLua.fromCart = false; return(true); }
public void Save(string file) { string extension = Path.GetExtension(file); byte[] data = null; switch (extension.ToLower()) { case ".bmp": data = BMP.Encode(this); break; case ".png": data = PNG.Encode(this); break; default: Debug.Assert(false, "Image file extension not supported: {0}", extension); break; } File.WriteAllBytes(file, data); }
static void Main(string[] args) { // add path to the input image to be compressed string sourceImagePath = @"E:\cs\c#\encoder v1\input.png"; var frame = new Frame(16, sourceImagePath); frame.importPNGFrame(sourceImagePath, ref frame); var compressedMatrix = new Double[frame.width, frame.height]; frameSegmentation(ref frame, frame.width, frame.height, frame.blockSize); // export frame as PNG var png = new PNG(frame, frame.width, frame.height, "compressed.png"); Console.ReadLine(); } // end Main()
public void WriteiTXtWithKeywordAndText() { PNG png = new PNG(@".\Resources\pngicon.png"); List <Chunk> iTXts = png.GetInternationalText("test"); Assert.AreEqual(iTXts.Count, 0); string text = "test text"; InternationalTextualDataChunk iTXt = new InternationalTextualDataChunk("test", text); png.AddTextualData(iTXt); iTXts = png.GetInternationalText("test"); Assert.AreEqual(iTXts.Count, 1); InternationalTextualDataChunk iTXtFinal = (InternationalTextualDataChunk)iTXts[0]; Assert.AreEqual(iTXtFinal.Text, text); }
private PNG formatPng(ImageModel imgMd) { try { FIBITMAP dib = FreeImage.Allocate(imgMd.width, imgMd.height, 32, 8, 8, 8); IntPtr pFibData = FreeImage.GetBits(dib); Marshal.Copy(imgMd.data, 0, pFibData, imgMd.data.Length); //FIMEMORY fm = new FIMEMORY(); FIMEMORY fm = FreeImage.OpenMemory(IntPtr.Zero, 0); FreeImage.SaveToMemory(FREE_IMAGE_FORMAT.FIF_PNG, dib, fm, FREE_IMAGE_SAVE_FLAGS.DEFAULT); FreeImage.SeekMemory(fm, 0, SeekOrigin.End); int bufferSize = FreeImage.TellMemory(fm); //Debug.WriteLine("aaa:" + bufferSize); FreeImage.SeekMemory(fm, 0, SeekOrigin.Begin); byte[] buffer = new byte[bufferSize]; FreeImage.ReadMemory(buffer, (uint)bufferSize, (uint)bufferSize, fm); FreeImage.CloseMemory(fm); FreeImage.Unload(dib); //using(FileStream fs = new FileStream("aaa_" + i + ".png", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)) { // fs.Write(buffer, 0, bufferSize); //} //using(FileStream fs = new FileStream("aaa.png", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write)) { // fs.Write(buffer, 0, bufferSize); //} PNG pngFrame = new PNG(); using (MemoryStream ms = new MemoryStream(buffer)) { pngFrame.Load(ms); } return(pngFrame); } catch (Exception) { } return(null); }
void workProc(object data) { ThreadWorkModel md = data as ThreadWorkModel; ThreadCollectModel thCollect = mdThreadCollect; do { if (md.needStop) { return; } const int waitTime = 10; Dictionary <int, ImageModel> mapData = new Dictionary <int, ImageModel>(); lock (md.lockCom) { foreach (int key in md.mapData.Keys) { mapData[key] = md.mapData[key]; } md.mapData = new Dictionary <int, ImageModel>(); } if (mapData.Count <= 0) { Thread.Sleep(waitTime); continue; } foreach (int key in mapData.Keys) { PNG png = formatPng(mapData[key]); lock (thCollect.lockCom) { thCollect.mapData[key] = png; } } } while(!md.needStop); }
/// <summary> /// Extract cartidge data to game folder /// </summary> public static void ExtractCartridge() { // FOLDER string path = GetRoot() + "/" + uRetroConfig.cartridgesFolder + "/" + uRetroConfig.cartridgeName; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = path + "/"; // CONFIG SaveRetroEngineConfig(); // COLORS PNG.Save(path + uRetroConfig.fileColors, uRetroColors.GetAsImage()); // SPRITES PNG.Save(path + uRetroConfig.fileSprites, uRetroSprites.GetAsImage()); // FONTS PNG.Save(path + uRetroConfig.fileFont, uRetroText.GetAsImage()); // TILEMAPS uRetroTilemap.Save(); // CODE File.WriteAllText(path + uRetroConfig.fileLua, uRetroLua.code); // INCLUDE for (int i = 0; i < uRetroLuaLibrary.include.Count; i++) { File.WriteAllText(path + uRetroLuaLibrary.include[i].name, uRetroLuaLibrary.include[i].code); } uRetroConsole.Print("Cartridge extracted to folder: " + uRetroConfig.cartridgeName); }
public string ServicePlacement(string virtual_json_str, string physical_json_str) { ParseInput(virtual_json_str, JsonStringType.Virtual); ParseInput(physical_json_str, JsonStringType.Physical); VNG.CalculateAllRC(); VNG.CalculateAllSAR(); VNG.SortNodeBySAR(); OutputMessage output = new OutputMessage(); while (VNG.SortedVirtualNodeDict.Any()) { PNG.CalculateAllRC(); VirtualNode vn = VNG.SortedVirtualNodeDict.Values.First(); PhysicalNode pn = PNG.GetMaxRCNode(); if (vn.RC <= pn.RC) { DeployVirtualNode(vn, pn); output.NodeMap.Add(vn, pn); VNG.SortedVirtualNodeDict.Remove(vn.ID); } else { output.State = "failed"; output.NodeMap = null; break; } } if (output.State != "failed") { output.State = "successful"; } return(EncapsulateOutput(output)); }
public void loadFromStream(Stream stream) { size = stream.Length; if (JPEG.test(stream)) { _img = new JPEG(stream); type = JPEG.MIME; ((JPEG)_img).extractHeaders(); // preserve headers for later meta = ((JPEG)_img).metaInfo(); } else if (PNG.test(stream)) { _img = new PNG(stream); type = PNG.MIME; } else { throw new ImageError(ImageError.WRONG_FORMAT); } Dictionary <string, int> info = _img.info(); if (info != null) { width = info["width"]; height = info["height"]; } BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(stream); _bm = new WriteableBitmap(bitmapImage); Load(this, null); }
public XORIDAT(PNG png, bool find = true) { image = png; ProcessPNG(find); }
public Reader(string path, string password = "") { pngOriginal = new PNG(path); this.password = password; }
public void Load(Stream stream) { chunks = new List <APNGChunk>(); pngs = new List <PNG>(); // Create a new header (should be 1 per file) and // read it from the stream var header = new APNGHeader(); try { header.Read(stream); } catch (Exception) { stream.Close(); throw; } APNGChunk chunk; PNG png = null; // Read chunks from the stream until we reach the MEND chunk do { // Read a generic Chunk chunk = new APNGChunk(); try { chunk.Read(stream); } catch (Exception) { stream.Close(); throw; } // Take a look at the chunk type and decide what derived class to // use to create a specific chunk switch (chunk.ChunkType) { case acTLChunk.NAME: if (headerChunk != null) { throw new ApplicationException(String.Format( "Only one chunk of type {0} is allowed", chunk.ChunkType)); } chunk = headerChunk = new acTLChunk(chunk); break; case MENDChunk.NAME: chunk = new MENDChunk(chunk); break; case TERMChunk.NAME: chunk = new TERMChunk(chunk); break; case BACKChunk.NAME: chunk = new BACKChunk(chunk); break; case BKGDChunk.NAME: chunk = new BKGDChunk(chunk); break; case fcTLChunk.NAME: // This is the beginning of a new embedded PNG chunk = new fcTLChunk(chunk); png = new PNG { FCTL = chunk as fcTLChunk, IHDR = ihdrChunk }; pngs.Add(png); break; case IHDRChunk.NAME: chunk = new IHDRChunk(chunk); ihdrChunk = chunk as IHDRChunk; break; case IDATChunk.NAME: chunk = new IDATChunk(chunk); if (png != null) { png.IDAT = chunk as IDATChunk; } break; case fdATChunk.NAME: chunk = new fdATChunk(chunk); if (png != null) { chunk.ChunkType = IDATChunk.NAME; png.IDAT = new IDATChunk(chunk); } break; case IENDChunk.NAME: chunk = new IENDChunk(chunk); for (var i = 0; i < pngs.Count; i++) { pngs[i].IEND = chunk as IENDChunk; } break; default: break; } // Add the chunk to our list of chunks chunks.Add(chunk); }while (chunk.ChunkType != IENDChunk.NAME); }
public async void WriteImageFile( string filePath, int width, int height, float offsetElevation, Vector2 lerpElevation, System.Action onFinish = null ) { //get file path from user: { if (filePath.Length == 0) { Debug.Log("Cancelled by user"); return; } if (IO.File.Exists(filePath) == false) { Debug.LogError($"File not found: { filePath }"); return; } } //prepare samples: Debug.Log($"Creating image...\nsource: { filePath }"); ushort[] pixels; { pixels = new ushort[height * width]; IO.FileStream stream = null; IO.StreamReader reader = null; await Task.Run(() => { try { stream = new IO.FileStream( filePath, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read ); reader = new IO.StreamReader(stream); int index = 0; // string line = null; while ((line = reader.ReadLine()) != null) { if (line.Length != 0) { //calc color value: float elevation = float.Parse(line) + offsetElevation; float inverselerped = Mathf.InverseLerp( lerpElevation.x, lerpElevation.y, elevation ); ushort color = (ushort)(inverselerped * ushort.MaxValue); // find pixel position int X = (width - 1) - index % width; int Y = (height - 1) - index / width; // set pixel color pixels[Y *width + X] = color; //step index++; } } } catch (System.Exception ex) { Debug.LogException(ex); } finally { if (stream != null) { stream.Close(); } if (reader != null) { reader.Close(); } } }); } //write bytes to file: { string pngFilePath = $"{ filePath.Replace(".csv","") } offset({ offsetElevation }) invlerp({ lerpElevation.x },{ lerpElevation.y }).png"; Debug.Log($"\twriting to PNG file: { pngFilePath }"); await PNG.WriteGrayscaleAsync( pixels : pixels, width : width, height : height, alpha : false, filePath : pngFilePath ); filePath = null; Debug.Log($"\tPNG file ready: { pngFilePath }"); } //call on finish: if (onFinish != null) { onFinish(); } }
public ColorCrash(PNG pngvector, bool find = true) : base(pngvector, find) { }
public static void CreateGame(string name) { uRetroConfig.cartridgeName = name; string path = GetRoot() + "/" + uRetroConfig.cartridgesFolder + "/" + uRetroConfig.cartridgeName; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = GetRoot() + "/" + uRetroConfig.cartridgesFolder + "/" + uRetroConfig.cartridgeName + "/"; Texture2D spr = Resources.Load("TemplateData/uRE_Sprites") as Texture2D; spr.filterMode = FilterMode.Point; spr.Apply(); PNG.Save(path + uRetroConfig.fileSprites, spr); Texture2D pal = Resources.Load("TemplateData/uRE_Colors") as Texture2D; pal.filterMode = FilterMode.Point; pal.Apply(); PNG.Save(path + uRetroConfig.fileColors, pal); Texture2D fnt = Resources.Load("TemplateData/uRE_Fonts") as Texture2D; fnt.filterMode = FilterMode.Point; fnt.Apply(); PNG.Save(path + uRetroConfig.fileFont, fnt); string code = @" function OnStart() end function OnUpdate(deltaTime) end function OnScanline(line) end function OnClose() end " ; File.WriteAllText(path + "main.lua", code); string tilemap = JsonConvert.SerializeObject(uRetroTilemap.layers, Formatting.Indented); Debug.Log(path + uRetroConfig.fileTilemap); File.WriteAllText(path + uRetroConfig.fileTilemap, tilemap); SaveRetroEngineConfig(); uRetroConsole.Show(); uRetroConsole.Print("Game folder with name '" + name + "' was created."); uRetroConsole.Print("Press [Alt+F4] for exit"); }
private void button_Unpack2_Click(object sender, EventArgs e) { InitializeJSON(); // create json string sdtextureoverridePath = textBox_Folder2.Text + SM_TEXTURES + "\\" + SM_TEXOVER; if (!Directory.Exists(Path.GetDirectoryName(sdtextureoverridePath))) { Directory.CreateDirectory(Path.GetDirectoryName(sdtextureoverridePath)); } using (FileStream stream = File.Open(sdtextureoverridePath, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Write(Resources.SDTextureOverride_SM2_Clean); } } // unpack mapped data from disk tac string tadFilepath = textBox_Folder2.Text + SM_ARCHIVE_DATA + SM2_DISK + ".tad"; string tacFilepath = textBox_Folder2.Text + SM_ARCHIVE_DATA + SM2_DISK + ".tac"; TAD tad = new TAD(tadFilepath); TAC tac = new TAC(tad); textures.Clear(); foreach (var entry in tad.Entries) { if (entry.FileName == "/misc/cold.bin") { continue; // not supported } byte[] buffer = tac.GetFileBuffer(entry); ReadFileRecursive(buffer); } bool first = true; string prevDdsPath = ""; string prevPngPath = ""; foreach (var tex in textures) { first = true; List <HashEntry> matches = new List <HashEntry>(); foreach (var t in SM2_Hashes) { if (tex.texID == t.texID) { if (first) // if first match, write DDS or PNG file { if (radioButton_DDS1.Checked) { DDS dds = new DDS(tex.image); string filepath = textBox_Folder2.Text + SM_TEXTURES + t.Filepath.Replace("/", "\\"); dds.MipHandling = DDSGeneral.MipHandling.KeepTopOnly; dds.AlphaSettings = DDSGeneral.AlphaSettings.KeepAlpha; dds.FormatDetails = new DDSFormats.DDSFormatDetails(DDSFormat.DDS_DXT3); dds.Write(filepath); prevDdsPath = filepath; } if (radioButton_PNG1.Checked) { PNG png = new PNG(tex.image); string filepath = textBox_Folder2.Text + SM_TEXTURES + t.Filepath.Replace("/", "\\"); string filepathPng = Path.ChangeExtension(filepath, ".png"); png.Write(filepathPng); prevPngPath = filepathPng; } first = false; } else // if duplicate, copy/paste the texture file (DDS and PNG writing costs alot of resources) { string filepath = textBox_Folder2.Text + SM_TEXTURES + t.Filepath.Replace("/", "\\"); string filepathPng = Path.ChangeExtension(filepath, ".png"); string dir = Path.GetDirectoryName(filepath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (radioButton_DDS1.Checked) { File.Copy(prevDdsPath, filepath, true); } if (radioButton_PNG1.Checked) { File.Copy(prevPngPath, filepathPng, true); } } matches.Add(t); } } // Remove matches to increase iteration speed, will result in the first found texture being used foreach (var match in matches) { SM2_Hashes.Remove(match); } } textures.Clear(); foreach (var hash in SM2_Hashes) { Console.WriteLine("Texture not found: {0} = {1}", hash.texID.HexStr, hash.Filepath); } }
private static string processFile(string path) { BMAP bmap = new BMAP(); string extension = Path.GetExtension(path).Substring(1); string outputName = ""; if (settings.Raw) { if (Raw.IsValid(path)) { Console.WriteLine("Loading : {0}", Path.GetFileName(path)); Raw.Load(path, true); return(path); } } else if (settings.Compress) { WreckfestExtensions we; if (Enum.TryParse <WreckfestExtensions>(extension, out we)) { using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path))) using (BinaryReader br = new BinaryReader(ms)) { if ( br.ReadInt32() != 4 || br.ReadByte() != extension[3] || br.ReadByte() != extension[2] || br.ReadByte() != extension[1] || br.ReadByte() != extension[0]) { br.BaseStream.Position = 0; var input = br.ReadBytes((int)ms.Length); File.Move(path, path + ".bak"); using (BinaryWriter bw = new BinaryWriter(new FileStream(path, FileMode.Create))) { bw.Write(4); bw.Write(extension[3]); bw.Write(extension[2]); bw.Write(extension[1]); bw.Write(extension[0]); bw.Write((int)we); var hashTable = new int[1 << (14 - 2)]; var output = new byte[LZ4Compress.CalculateChunkSize(input.Length)]; int i = 0; while (i < input.Length) { byte[] chunk = new byte[Math.Min(input.Length - i, output.Length)]; Array.Copy(input, i, chunk, 0, chunk.Length); Array.Clear(hashTable, 0, hashTable.Length); int size = LZ4Compress.Compress(hashTable, chunk, output, chunk.Length, chunk.Length + 4); bw.Write(size); bw.Write(output, 0, size); i += chunk.Length; } } } else { Console.WriteLine("Skipping : {0} is already compressed", Path.GetFileName(path)); } } } else { Console.WriteLine("Error : unsupported extension '{0}'.", extension); } } else if (extension == "bmap") { if (BMAP.IsBMAP(path)) { Console.WriteLine("Loading : {0}", Path.GetFileName(path)); bmap = BMAP.Load(path, false); outputName = string.Format("{0}.{1}.png", Path.GetFileNameWithoutExtension(path), (bmap.Mode == 1 ? "clutter" : (bmap.DDS.Format == D3DFormat.A8R8G8B8 ? "raw" : bmap.DDS.Format.ToString().ToLower()))); Console.WriteLine("Saving : {0}", outputName); if (!Overwrite(string.Format(@"{0}\{1}", Path.GetDirectoryName(path), outputName))) { return(null); } bmap.SaveAsPNG(outputName); return(path); } } else if (extension == "dds") { Console.WriteLine("Loading : {0}", Path.GetFileName(path)); bmap.Path = Path.GetFileName(path); bmap.DDS = DDS.Load(path); Console.WriteLine("Saving : {0}", Path.GetFileName(path.Replace(".dds", ".bmap"))); bmap.Save(path.Replace(".dds", ".x.bmap")); return(path); } else if (Array.IndexOf(new string[] { "png", "tga", "tif" }, extension) > -1) { Texture texture = null; Console.WriteLine("Loading : {0}", Path.GetFileName(path)); switch (extension) { case "png": texture = PNG.Load(path); break; case "tga": texture = TGA.Load(path); break; case "tif": texture = TIF.Load(path); break; } BreckfestSettings original = settings.Clone(); if (Path.GetFileNameWithoutExtension(path).EndsWith(".clutter", StringComparison.OrdinalIgnoreCase)) { settings.Clutter = true; path = path.Replace(".clutter", ""); } else if (Path.GetFileNameWithoutExtension(path).EndsWith(".raw", StringComparison.OrdinalIgnoreCase)) { settings.Format = D3DFormat.A8R8G8B8; path = path.Replace(".raw", ""); } else if (Path.GetFileNameWithoutExtension(path).EndsWith(".dxt1", StringComparison.OrdinalIgnoreCase)) { settings.Format = D3DFormat.DXT1; path = path.Replace(".dxt1", ""); } else if (Path.GetFileNameWithoutExtension(path).EndsWith(".dxt5", StringComparison.OrdinalIgnoreCase)) { settings.Format = D3DFormat.DXT5; path = path.Replace(".dxt5", ""); } bmap.Path = Path.GetFileName(path); if (settings.Clutter) { Console.WriteLine("Cluttering: {0}x{1}", texture.Bitmap.Width, texture.Bitmap.Height); bmap.Mode = 1; bmap.Raw = texture.Bitmap; } else { if (settings.Format == D3DFormat.A8R8G8B8) { Console.WriteLine("Formatting: {0}x{1} (this might take awhile)", texture.Bitmap.Width, texture.Bitmap.Height); } else { Console.WriteLine("Squishing : {0}x{1} (this might take awhile)", texture.Bitmap.Width, texture.Bitmap.Height); } bmap.DDS = new DDS(settings.Format, texture.Bitmap); } Console.WriteLine("Saving : {0}", Path.GetFileName(path.Replace(string.Format(".{0}", extension), ".bmap"))); bmap.Save(path.Replace(string.Format(".{0}", extension), ".x.bmap"), true); settings = original.Clone(); return(path); } return(null); }
private void button_Convert_Click(object sender, EventArgs e) { string outputFolder = textBox_OutputFolder.Text; if (String.IsNullOrEmpty(outputFolder)) { return; } if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } List <BaseImage> images = new List <BaseImage>(); if (checkBox_ConvertSelected.Checked) { foreach (BaseImage img in listBox_Images.SelectedItems) { images.Add(img); } } else { foreach (BaseImage img in listBox_Images.Items) { images.Add(img); } } if ((Type)comboBox_ImageFormat.SelectedItem == typeof(PVRT)) { PVRTSettings settings = pvrtControl.Settings; foreach (BaseImage image in images) { PVRT pvrt = new PVRT(image); pvrt.PixelFormat = settings.PixelFormat; pvrt.DataFormat = settings.DataFormat; if (settings.CreateTEXN) { string srcFilename = Path.GetFileName(image.FilePath); string[] splitted = srcFilename.Split('.'); string texIDString = splitted[0]; UInt64 texID = Convert.ToUInt64(texIDString, 16); TEXN texn = new TEXN(); texn.TextureID.Data = texID; string filename = String.Format("{0}.{1}.TEXN", Helper.ByteArrayToString(BitConverter.GetBytes(texn.TextureID.Data)), texn.TextureID.Name.Replace("\0", "_")); string filepath = outputFolder + "\\" + filename; using (FileStream fileStream = new FileStream(filepath, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { long offset = fileStream.Position; texn.WriteHeader(writer); if (settings.InsertDDS && typeof(DDS).IsAssignableFrom(image.GetType())) { pvrt.WriteDDSRaw(writer, (DDS)image); } else { pvrt.Write(writer); } texn.EntrySize = (uint)(fileStream.Position - offset); fileStream.Seek(offset, SeekOrigin.Begin); texn.WriteHeader(writer); } } } else { string filepath = outputFolder + "\\" + Path.ChangeExtension(Path.GetFileName(image.FilePath), ".PVR"); using (FileStream fileStream = new FileStream(filepath, FileMode.Create)) { using (BinaryWriter writer = new BinaryWriter(fileStream)) { if (settings.InsertDDS && typeof(DDS).IsAssignableFrom(image.GetType())) { pvrt.WriteDDSRaw(writer, (DDS)image); } else { pvrt.Write(writer); } } } } } } else if ((Type)comboBox_ImageFormat.SelectedItem == typeof(DDS)) { DDSSettings settings = ddsControl.Settings; foreach (BaseImage image in images) { string filepath = outputFolder + "\\" + Path.ChangeExtension(Path.GetFileName(image.FilePath), ".dds"); DDS dds = new DDS(image); dds.AlphaSettings = settings.AlphaSettings; dds.MipHandling = settings.MipHandling; dds.FormatDetails = new DDSFormats.DDSFormatDetails(settings.DDSFormat, settings.DXGIFormat); dds.Write(filepath); } } else if ((Type)comboBox_ImageFormat.SelectedItem == typeof(PNG)) { foreach (BaseImage image in images) { string filepath = outputFolder + "\\" + Path.ChangeExtension(Path.GetFileName(image.FilePath), ".png"); PNG png = new PNG(image); png.Write(filepath); } } else if ((Type)comboBox_ImageFormat.SelectedItem == typeof(BMP)) { foreach (BaseImage image in images) { string filepath = outputFolder + "\\" + Path.ChangeExtension(Path.GetFileName(image.FilePath), ".bmp"); BMP bmp = new BMP(image); bmp.Write(filepath); } } else if ((Type)comboBox_ImageFormat.SelectedItem == typeof(JPEG)) { foreach (BaseImage image in images) { string filepath = outputFolder + "\\" + Path.ChangeExtension(Path.GetFileName(image.FilePath), ".jpg"); JPEG jpg = new JPEG(image); jpg.Write(filepath); } } }
void LoadImage(string path) { pngOriginal = new PNG(path); using (MemoryStream stream = new MemoryStream()) { if (imgOriginal.Image != null) { imgOriginal.Image.Dispose(); } pngOriginal.WriteToStream(stream, true, true); stream.Seek(0, SeekOrigin.Begin); Image img = Image.FromStream(stream); imgOriginal.Image = img; imghandler(imgOriginal, null); } lblNoFile.Visible = false; List <Provider> providers = new List <Provider>(Program.Providers); bool hasEOF = false; bool hasTXT = false; int IDATs = 0; foreach (PNGChunk chunk in pngOriginal.Chunks) { if (chunk.Name == "_EOF") { hasEOF = true; } if (chunk.Name == "tEXt") { hasTXT = true; } if (chunk.Name == "IDAT") { IDATs++; } } if (hasEOF) { providers.Add(Program.XOREOF); } if (hasTXT) { providers.Add(Program.XORTXT); } if (IDATs > 1) { providers.Add(Program.XORIDAT); } Provider pr = null; if (providers.Count > 0) { using (SelectProvider prov = new SelectProvider(providers.ToArray())) { prov.ShowDialog(); pr = prov.SelectedProvider; } } providers = null; if (pr == null) { provider = null; SetHidden(DataType.None, null); tabs.SelectedIndex = 0; } else { try { provider = (SteganographyProvider)Activator.CreateInstance(pr.ProviderType, pngOriginal, true); DisposeHidden(); object data; DataType t = provider.Extract(out data); hidden = data; SetHidden(t, data); hiddent = t; if (t != DataType.None) { menuActionDumpHidden.Enabled = true; } } catch (InvalidPasswordException) { provider = null; SetHidden(DataType.None, null); tabs.SelectedIndex = 0; MessageBox.Show(this, "The password you entered was incorrect.", "Incorrect Password", MessageBoxButtons.OK, MessageBoxIcon.Error); } } tabs.Enabled = true; menuActionInject.Enabled = true; menuActionDumpOriginal.Enabled = true; pngOriginal.RemoveNonCritical(); }
static void Main(string[] args) { PNG p = new PNG(); }
Bitmap extract_png(PNG png, wz_file f) { DeflateStream zlib; int size_png = 0; int x = 0, y = 0, b = 0, g = 0; Bitmap png_decoded = null; BitmapData bmp_data; byte[] plain_data; f.stream.Position = png.offs; if(f.bStream.ReadUInt16() == 0x9C78) { zlib = new DeflateStream(f.stream, CompressionMode.Decompress); } else { f.stream.Position -= 2; MemoryStream data_stream = new MemoryStream(); int blocksize = 0; int end_of_png = (int)(png.data_length + f.stream.Position); while(f.stream.Position < end_of_png){ blocksize = f.bStream.ReadInt32(); for(int i = 0; i < blocksize; i++) { data_stream.WriteByte((byte)(f.bStream.ReadByte() ^ WZ.encryption.keys[i])); } } data_stream.Position = 2; zlib = new DeflateStream(data_stream, CompressionMode.Decompress); } switch (png.form) { case 1: png_decoded = new Bitmap(png.w, png.h, PixelFormat.Format32bppArgb); bmp_data = png_decoded.LockBits(new Rectangle(0, 0, png.w, png.h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); size_png = png.w * png.h * 2; plain_data = new byte[size_png]; zlib.Read(plain_data, 0, size_png); byte[] argb = new Byte[size_png * 2]; for (int i = 0; i < size_png; i++) { b = plain_data[i] & 0x0F; b |= (b << 4); argb[i * 2] = (byte)b; g = plain_data[i] & 0xF0; g |= (g >> 4); argb[i * 2 + 1] = (byte)g; } Marshal.Copy(argb, 0, bmp_data.Scan0, argb.Length); png_decoded.UnlockBits(bmp_data); break; case 2: png_decoded = new Bitmap(png.w, png.h, PixelFormat.Format32bppArgb); bmp_data = png_decoded.LockBits(new Rectangle(0, 0, png.w, png.h), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); size_png = png.w * png.h * 4; plain_data = new byte[size_png]; zlib.Read(plain_data, 0, size_png); Marshal.Copy(plain_data, 0, bmp_data.Scan0, plain_data.Length); png_decoded.UnlockBits(bmp_data); break; case 513: png_decoded = new Bitmap(png.w, png.h, PixelFormat.Format16bppRgb565); bmp_data = png_decoded.LockBits(new Rectangle(0, 0, png.w, png.h), ImageLockMode.WriteOnly, PixelFormat.Format16bppRgb565); size_png = png.w * png.h * 2; plain_data = new byte[size_png]; zlib.Read(plain_data, 0, size_png); Marshal.Copy(plain_data, 0, bmp_data.Scan0, plain_data.Length); png_decoded.UnlockBits(bmp_data); break; case 517: png_decoded = new Bitmap(png.w, png.h); size_png = png.w * png.h / 128; plain_data = new byte[size_png]; zlib.Read(plain_data, 0, size_png); byte iB = 0; for (int i = 0; i < size_png; i++) { for (byte j = 0; j < 8; j++) { iB = Convert.ToByte(((plain_data[i] & (0x01 << (7 - j))) >> (7 - j)) * 0xFF); for (int k = 0; k < 16; k++) { if (x == png.w) { x = 0; y++; } png_decoded.SetPixel(x, y, Color.FromArgb(0xFF, iB, iB, iB)); x++; } } } break; } return png_decoded; }