public static void SaveAsPng(this Texture2D texture, Stream stream) { switch (texture.Format) { case SurfaceFormat.Bgra4444: byte[] data = new byte[texture.Width * texture.Height * 2]; texture.GetTexture_BGRA4444(data); data = WzLib.Wz_Png.GetPixelDataBgra4444(data, texture.Width, texture.Height); unsafe { fixed(byte *pData = data) { using (var bmp = new System.Drawing.Bitmap(texture.Width, texture.Height, texture.Width * 4, System.Drawing.Imaging.PixelFormat.Format32bppArgb, new IntPtr(pData))) { bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png); } } } break; default: texture.SaveAsPng(stream, texture.Width, texture.Height); break; } }
public static OcclusionMap Generate() { //Make room for edges which are always walls. bool[,] space = new bool[260 - 2, 260 - 2]; for (int i = 0; i != 200; i++) { for (int j = 0; j != 200; j++) { space[i, j] = true; } } Texture2D Map = new Texture2D(Renderer.GraphicsDevice,260, 260); Color[] color = new Color[260 * 260]; for (int i = 0; i != 260; i++) { for (int j = 0; j != 260; j++) { color[i * 260 + j] = ( i != 0 && j != 0 && i != 259 && j != 259 && space[i-1,j-1] ? FloorColor : WallColor); } } Map.SetData(color); Stream stream = File.Create("test.png"); Map.SaveAsPng(stream, 260, 260); return null; }
public static System.Drawing.Image Texture2Image(Texture2D texture) { if (texture == null) { return null; } if (texture.IsDisposed) { return null; } //Memory stream to store the bitmap data. MemoryStream ms = new MemoryStream(); //Save the texture to the stream. texture.SaveAsPng(ms, texture.Width, texture.Height); //Seek the beginning of the stream. ms.Seek(0, SeekOrigin.Begin); //Create an image from a stream. System.Drawing.Image bmp2 = System.Drawing.Bitmap.FromStream(ms); //Close the stream, we nolonger need it. ms.Close(); ms = null; return bmp2; }
//TODO: monogame does not support SaveAsXXX and mono does not implement gzipstream properly //TODO: find a fix for linux public static string SaveTextureData(Texture2D texture) { var streamOut = new MemoryStream(); var width = texture.Width; var height = texture.Height; texture.SaveAsPng(streamOut, width, height); return Convert.ToBase64String(streamOut.ToArray()); }
public System.Drawing.Image ConvertToImage(Texture2D source) { if (source == null) return null; MemoryStream mem = new MemoryStream(); source.SaveAsPng(mem, source.Width, source.Height); return System.Drawing.Image.FromStream(mem); }
/// <summary> /// Stores the current contents of the back buffer as a .PNG file. /// </summary> /// <param name="inGraphicsDevice">GraphicsDevice to grab the back buffer data from.</param> /// <param name="inFilename">String containing the name of the file to save.</param> /// <returns>True if the file is saved successfully, otherwise false.</returns> public static bool Capture(GraphicsDevice inGraphicsDevice, String inFilename, ScreenCaptureType inCaptureExtension) { if (inCaptureExtension == ScreenCaptureType.UseJPEG) { inFilename = inFilename + ".jpg"; } if (inCaptureExtension == ScreenCaptureType.UsePNG) { inFilename = inFilename + ".png"; } // Store the current BackBuffer data in a new array of Color values. This // will take what is currently on the BackBuffer; everything current being // drawn to the screen. Color[] colorData = new Color[inGraphicsDevice.Viewport.Width * inGraphicsDevice.Viewport.Height]; inGraphicsDevice.GetBackBufferData<Color>(colorData); // Next set the colors into a Texture, ready for saving. Texture2D backBufferTexture = new Texture2D(inGraphicsDevice, inGraphicsDevice.Viewport.Width, inGraphicsDevice.Viewport.Height); backBufferTexture.SetData<Color>(colorData, 0, colorData.Length); // Create the file after checking whether it exists. This requires a means // of altering the intended filename so that it cannot overwrite an existing // screen-capture, for instance suffixing an incremental digit onto the file // name, but this would have to be saved to avoid overwritten files when the // game crashes and the count is lost. if (!File.Exists(inFilename)) { using (FileStream fileStream = File.Create(inFilename)) { // The choice passed in as the 3rd parameter just exists for the sake // of providing options. If one is clearly advantageous to the other // I'll hard-code it to use that instead. But, for now, we allow the // choice between JPEG and PNG. PNG files have transparency. switch (inCaptureExtension) { case ScreenCaptureType.UseJPEG: backBufferTexture.SaveAsJpeg(fileStream, inGraphicsDevice.Viewport.Width, inGraphicsDevice.Viewport.Height); break; case ScreenCaptureType.UsePNG: backBufferTexture.SaveAsPng(fileStream, inGraphicsDevice.Viewport.Width, inGraphicsDevice.Viewport.Height); break; } fileStream.Flush(); } return true; } return false; }
void SaveTexture(IResource resource, Texture2D texture) { if (texture == null) return; using (var stream = resource.Create()) { // PNG only. texture.SaveAsPng(stream, texture.Width, texture.Height); texture.Name = resource.AbsoluteUri; } }
public bool Write(string path, Texture2D texture) { if (!File.Exists(DataFolder + "\\data")) { Helper.mkdir(DataFolder + "\\data"); } Stream stream = new FileStream(DataFolder + "\\data\\" + path.Replace("/", "-"), FileMode.OpenOrCreate); texture.SaveAsPng(stream, texture.Bounds.Width, texture.Bounds.Height); return true; }
public static Image ImageFromTexture(Texture2D Source) { Image ToReturn; MemoryStream MStream = new MemoryStream(); Source.SaveAsPng(MStream, Source.Width, Source.Height); ToReturn = Image.FromStream(MStream); MStream.Dispose(); MStream = null; GC.Collect(); return ToReturn; }
/// <summary> /// Opens dialog for user to save screenshot /// </summary> /// <param name="texture2D">Takes in texture2D for screen information</param> private static void saveScreenshot(Texture2D texture2D) { SaveFileDialog saveScreenshot = new SaveFileDialog(); saveScreenshot.DefaultExt = ".png"; saveScreenshot.ShowDialog(); saveScreenshot.CreatePrompt = true; if (saveScreenshot.FileName != string.Empty) { Stream stream = new FileStream(saveScreenshot.FileName, FileMode.Create); texture2D.SaveAsPng(stream, texture2D.Width, texture2D.Height); stream.Close(); } }
public void MakeScreenshot(string fileName) { var width = (int)window.ViewportPixelSize.Width; var height = (int)window.ViewportPixelSize.Height; using (var dstTexture = new Texture2D(device.NativeDevice, width, height, false, device.NativeDevice.PresentationParameters.BackBufferFormat)) { var pixelColors = new Color[width * height]; device.NativeDevice.GetBackBufferData(pixelColors); dstTexture.SetData(pixelColors); using (var stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) dstTexture.SaveAsPng(stream, width, height); } }
public void SetTextureSlot(int _nSlotIdx, Texture2D _tex) { if (_nSlotIdx < 0 || _nSlotIdx >= SlotsCount) return; MemoryStream mem = new MemoryStream(); _tex.SaveAsPng(mem, 256, 256); m_imagesSlots[_nSlotIdx] = Image.FromStream(mem); Game1.SetTextureSlot(_nSlotIdx, _tex); Refresh(); }
public static void createTexture( GraphicsDevice graphics, string name, byte format, int width, int height, uint[] colorData) { Stream fStream = new FileStream(name, FileMode.CreateNew); Texture2D outputTexture = new Texture2D(graphics, width, height, false, SurfaceFormat.Color); outputTexture.SetData<uint>(colorData); outputTexture.SaveAsPng(fStream, width, height); }
//, Texture2D textureB) public static void copyTexture( GraphicsDevice graphics, string name, Texture2D sourceTexture, SurfaceFormat format) { Stream fStream = new FileStream(name, FileMode.CreateNew); uint[] colorData = new uint[sourceTexture.Width * sourceTexture.Height]; sourceTexture.GetData<uint>(colorData); Texture2D outputTexture = new Texture2D(graphics, sourceTexture.Width, sourceTexture.Height, false, format); outputTexture.SetData<uint>(colorData); outputTexture.SaveAsPng(fStream, outputTexture.Width, outputTexture.Height); }
public override sealed void UpdateUi(Object value) { if (value != _currentTexture) { _currentTexture = value as Texture2D; if (_currentTexture == null) return; using (var pngImage = new MemoryStream()) { _currentTexture.SaveAsPng(pngImage, 20, 20); var bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.DecodePixelWidth = 20; bi.StreamSource = pngImage; bi.EndInit(); pngImage.Close(); Image.Source = bi; } } }
public void ScreenShot() { int w = GraphicsDevice.PresentationParameters.BackBufferWidth; int h = GraphicsDevice.PresentationParameters.BackBufferHeight; //force a frame to be drawn (otherwise back buffer is empty) Draw(new GameTime()); //pull the picture from the buffer int[] backBuffer = new int[w * h]; GraphicsDevice.GetBackBufferData(backBuffer); //copy into a texture Texture2D texture = new Texture2D(GraphicsDevice, w, h, false, GraphicsDevice.PresentationParameters.BackBufferFormat); texture.SetData(backBuffer); //save to disk Stream stream = System.IO.File.OpenWrite("screenshot_" + File + ".png"); texture.SaveAsPng(stream, w, h); stream.Close(); }
public static void ScreenShot(string prefix) { GraphicsDevice graphics = (GraphicsDevice)typeof(Terraria.Main).GetField("GraphicsDevice").GetValue(null); //typeof(Terraria.Main).get int w = graphics.PresentationParameters.BackBufferWidth; int h = graphics.PresentationParameters.BackBufferHeight; //强行调用一次Draw,用当前屏幕覆盖back buffer //Draw(new GameTime()); //拷贝backbuffer int[] backBuffer = new int[w * h]; graphics.GetBackBufferData(backBuffer); //拷贝至texture Texture2D texture = new Texture2D(graphics, w, h, false, graphics.PresentationParameters.BackBufferFormat); texture.SetData(backBuffer); //保存 Stream stream = File.OpenWrite(prefix + "_" + Guid.NewGuid().ToString() + ".png"); texture.SaveAsPng(stream, w, h); stream.Close(); }
public Minimap(Texture2D map, Texture2D nestTex, Texture2D labTex, GraphicsDevice graphics) { int divisor = (int)Math.Pow(2.0, (double)MIPMAP_LEVEL); int width = map.Width/divisor; int height = map.Height/divisor; // Data for MipMaps Color[] mapData = new Color[width * height]; Color[] nestData = new Color[(nestTex.Width / divisor) * (nestTex.Height / divisor)]; Color[] labData = new Color[(labTex.Width / divisor) * (labTex.Height / divisor)]; // Get MipMap Data map.GetData<Color>(MIPMAP_LEVEL,null, mapData, 0, mapData.Length); nestTex.GetData<Color>(MIPMAP_LEVEL, null, nestData, 0, nestData.Length); labTex.GetData<Color>(MIPMAP_LEVEL, null, labData, 0, labData.Length); // Create Minimap minimap = new Texture2D(graphics, width, height); minimap.SetData<Color>(mapData); // Impose Nest Textures for (int x = 0; x < map.Width; x+=GameHandler.TileMap.TileWidth) for (int y = 0; y < map.Height; y+=GameHandler.TileMap.TileHeight) if (GameHandler.CheckNests(new Rectangle(x, y, GameHandler.TileMap.TileWidth, GameHandler.TileMap.TileHeight))) minimap.SetData<Color>(0, new Rectangle(x/divisor, y/divisor, nestTex.Width / divisor, nestTex.Height / divisor), nestData, 0, nestData.Length); // Impose Lab Texture minimap.SetData<Color>(0, new Rectangle((int)GameHandler.TileMap.LabPosition.X / divisor, (int)GameHandler.TileMap.LabPosition.Y/ divisor, labTex.Width / divisor, labTex.Height / divisor), labData, 0, labData.Length); if (File.Exists(Directory.GetCurrentDirectory() + "/~minimap.png")) File.Delete(Directory.GetCurrentDirectory() + "/~minimap.png"); Stream stream = File.OpenWrite("~minimap.png"); minimap.SaveAsPng(stream, minimap.Width, minimap.Height); stream.Close(); }
public static bool CapturePng(GraphicsDevice inGraphicsDevice, String inFilename) { inFilename = inFilename + ".png"; // Store the current BackBuffer data in a new array of Color values. This // will take what is currently on the BackBuffer; everything current being // drawn to the screen. Color[] colorData = new Color[inGraphicsDevice.Viewport.Width * inGraphicsDevice.Viewport.Height]; inGraphicsDevice.GetBackBufferData<Color>(colorData); // Next set the colors into a Texture, ready for saving. Texture2D backBufferTexture = new Texture2D(inGraphicsDevice, inGraphicsDevice.Viewport.Width, inGraphicsDevice.Viewport.Height); backBufferTexture.SetData<Color>(colorData, 0, colorData.Length); // Create the file after checking whether it exists. This requires a means // of altering the intended filename so that it cannot overwrite an existing // screen-capture, for instance suffixing an incremental digit onto the file // name, but this would have to be saved to avoid overwritten files when the // game crashes and the count is lost. if (!File.Exists(inFilename)) { using (FileStream fileStream = File.Create(inFilename)) { backBufferTexture.SaveAsPng(fileStream, inGraphicsDevice.Viewport.Width, inGraphicsDevice.Viewport.Height); fileStream.Flush(); } return true; } return false; }
public void ScreenShot(string prefix) { int w = GraphicsDevice.PresentationParameters.BackBufferWidth; int h = GraphicsDevice.PresentationParameters.BackBufferHeight; //force a frame to be drawn (otherwise back buffer is empty) Draw(new GameTime()); //pull the picture from the buffer int[] backBuffer = new int[w * h]; GraphicsDevice.GetBackBufferData(backBuffer); //copy into a texture Texture2D texture = new Texture2D(GraphicsDevice, w, h, false, GraphicsDevice.PresentationParameters.BackBufferFormat); texture.SetData(backBuffer); //save to disk Stream stream = File.OpenWrite(prefix + ".png"); texture.SaveAsPng(stream, w, h); texture.Dispose(); stream.Close(); Console.WriteLine("Screenshot saved in the root directory."); }
/// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public void Update(GameTime gameTime) { // Get input from the player inputController.Update(); // screencaps if (inputController.ScreenCap.JustPressed) { Draw(gameTime); Texture2D texture = new Texture2D(graphicsDevice, GraphicsConstants.VIEWPORT_WIDTH, GraphicsConstants.VIEWPORT_HEIGHT); Color[] data = new Color[texture.Width * texture.Height]; graphicsDevice.GetBackBufferData<Color>(data); texture.SetData<Color>(data); Stream stream = File.OpenWrite("output.png"); texture.SaveAsPng(stream, texture.Width, texture.Height); stream.Dispose(); texture.Dispose(); } if (currentContext.Exit || currentContext.NextContext != null) { targetOverlayAlpha = 1; if (currentOverlayAlpha == 1) { //audioPlayer.StopSong(); if (currentContext.Exit) exitGame = true; else if (!asyncStarted) { asyncStarted = true; asyncFinished = false; InitializeContextComponents(currentContext.NextContext); asyncFinished = true; } if (asyncStarted && asyncFinished) { //Thread.Sleep(1000); asyncStarted = false; targetOverlayAlpha = 0; currentContext.Dispose(); currentContext = currentContext.NextContext; } } } else { currentContext.Update(gameTime); } currentOverlayAlpha = MathHelper.Lerp(currentOverlayAlpha, targetOverlayAlpha, currentContext.FadeMultiplier); //Console.WriteLine(Math.Abs(currentOverlayAlpha - targetOverlayAlpha)); if (Math.Abs(currentOverlayAlpha - targetOverlayAlpha) < 0.001f || inputController.Zoom.Pressed) currentOverlayAlpha = targetOverlayAlpha; }
public static Image TextureToImage(Texture2D texture, int width, int height) { MemoryStream ms = new MemoryStream(); texture.SaveAsPng(ms, width, height); return Image.FromStream(ms); }
public void GenerateSpriteSheet(int width, int height, int safeBorderSize, String outputPath, String sheetName) { if (checkBoxPowerOf2.Checked == true) { // if not a power of 2 already if ((width & (width - 1)) != 0) { width = GetNextPowerOf2(width); } if ((height & (height - 1)) != 0) { height = GetNextPowerOf2(height); } } bool overrideTransColor = checkBoxOverrideBaseColor.Checked; XnaColor baseColor = XnaColor.Black; if (overrideTransColor == true) { baseColor = new XnaColor(this.BaseTextureColor.R, this.BaseTextureColor.G, this.BaseTextureColor.B, 0); } uint[] destinationData = new uint[width * height]; for (int i = 0; i < destinationData.Length; i++) { destinationData[i] = baseColor.PackedValue; } Texture2D spriteSheet = new Texture2D(IceCream.Drawing.DrawingManager.GraphicsDevice, width, height); foreach (SpriteInfo sprite in this.Sprites) { Texture2D source = sprite.Texture2D; int x = sprite.X; int y = sprite.Y; int w = source.Width; int h = source.Height; int b = safeBorderSize; int sourceSize = sprite.Texture2D.Width; int destSize = width; // Copy the main sprite data to the output sheet. sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(0, 0, w, h), ref destinationData, destSize, new Point(x + b, y + b), baseColor.PackedValue, overrideTransColor); // Copy a border strip from each edge of the sprite, creating // a padding area to avoid filtering problems if the // sprite is scaled or rotated. for (int i = 0; i < safeBorderSize; i++) { sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(0, 0, 1, h), ref destinationData, destSize, new Point(x + i, y + b), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(w - 1, 0, 1, h), ref destinationData, destSize, new Point(x + w + i + b, y + b), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(0, 0, w, 1), ref destinationData, destSize, new Point(x + b, y + i), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(0, h - 1, w, 1), ref destinationData, destSize, new Point(x + b, y + h + i + b), baseColor.PackedValue, overrideTransColor); // Copy a single pixel from each corner of the sprite, // filling in the corners of the padding area. for (int j = 0; j < b; j++) { sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(0, 0, 1, 1), ref destinationData, destSize, new Point(x + j, y + i), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(0, 0, 1, 1), ref destinationData, destSize, new Point(x + i, y + j), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(w - 1, 0, 1, 1), ref destinationData, destSize, new Point(x + w + b + i, y + j), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(w - 1, 0, 1, 1), ref destinationData, destSize, new Point(x + w + b + j, y + i), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(0, h - 1, 1, 1), ref destinationData, destSize, new Point(x + i, y + h + b + j), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(0, h - 1, 1, 1), ref destinationData, destSize, new Point(x + j, y + h + b + i), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(w - 1, h - 1, 1, 1), ref destinationData, destSize, new Point(x + w + b + i, y + h + b + j), baseColor.PackedValue, overrideTransColor); sprite.CopyPixels(sprite.PixelData, sourceSize, new Rectangle(w - 1, h - 1, 1, 1), ref destinationData, destSize, new Point(x + w + b + j, y + h + b + i), baseColor.PackedValue, overrideTransColor); } } sprite.Area = new Rectangle(x + safeBorderSize, y + safeBorderSize, sprite.Texture2D.Width, sprite.Texture2D.Height); } if (checkBoxAlphaCorrection.Checked == true) { CorrectAlphaBorders(destinationData, width, height, 2); } spriteSheet.SetData<uint>(destinationData); String outputFilename = Path.Combine(outputPath, sheetName + ".png"); using (Stream stream = File.OpenWrite(outputFilename)) { spriteSheet.SaveAsPng(stream, spriteSheet.Width, spriteSheet.Height); } ExportXML(Path.Combine(outputPath, sheetName + ".xml")); }
/// <summary> /// Create bitmap containing heightmap data. /// </summary> /// <param name="filepath"></param> public MemoryStream ExportToStream() { Texture2D heightMapTexture = new Texture2D(mDevice, mWidth, mHeight); Color[] heightTexels = new Color[mWidth * mHeight]; for (int row = 0; row < mHeight; ++row) { for (int col = 0; col < mWidth; ++col) { heightTexels[col + row * mWidth] = HeightAsColor((int)mVertices[col + row * mWidth].Position.Y); } } heightMapTexture.SetData(heightTexels); MemoryStream ms = new MemoryStream(); heightMapTexture.SaveAsPng(ms, mWidth, mHeight); ms.Seek(0, SeekOrigin.Begin); return ms; }
private void ProcessImage( string outputDir ) { string outfileBase = outputDir + @"\" + txtOutFileBaseName.Text; Rectangle frame = new Rectangle( 0, 0, (int)nudCutWidth.Value, (int)nudCutHeight.Value ); Texture2D workingImg = new Texture2D( gd, frame.Width, frame.Height ); int count = 0; int numRows = originalImg.Height / frame.Height; int numCols = originalImg.Width / frame.Width; int numPixels = frame.Width * frame.Height; for ( int i = 0; i < numRows; i++ ) { frame.Y = i * frame.Height; for ( int j = 0; j < numCols; j++ ) { frame.X = j * frame.Width; Color[] cpy = new Color[numPixels]; originalImg.GetData<Color>( 0, frame, cpy, 0, numPixels ); workingImg.SetData<Color>( cpy ); // Save the image Stream s; switch ( cmbOutFileType.SelectedIndex ) { case 0: s = File.OpenWrite( outfileBase + count.ToString() + ".png" ); workingImg.SaveAsPng( s, workingImg.Width, workingImg.Height ); s.Close(); break; case 1: s = File.OpenWrite( outfileBase + count.ToString() + ".jpg" ); workingImg.SaveAsJpeg( s, workingImg.Width, workingImg.Height ); s.Close(); break; default: break; } count++; } } MessageBox.Show( "Created " + count.ToString() + " tiles!", "Processing Done!" ); }
public void saveDensity() { GraphicsDevice device = GameServices.GetService<GraphicsDeviceManager>().GraphicsDevice; Texture2D tex = new Texture2D(device, m_w, m_h, false, SurfaceFormat.Color); if (File.Exists("mucus" + m_w + "x" + m_h + ".png")) return; Stream stream = File.OpenWrite("mucus" + m_w + "x" + m_h + ".png"); tex.SetData(texData); tex.SaveAsPng(stream, m_w, m_h); }
/// <summary> /// Create and save two textures: /// heightTexture.png /// colorTexture.png /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); device = graphics.GraphicsDevice; heightTexture = createHeightTexture(); // MonoGames hasn't implemented SaveAsPng(...) // will compile, but throws NotImplementedException. #if __XNA4__ using (Stream stream = File.OpenWrite("heightTexture.png")) { heightTexture.SaveAsPng(stream, textureWidth, textureHeight); } #endif colorTexture = createColorTexture(); #if __XNA4__ using (Stream stream = File.OpenWrite("colorTexture.png")) { colorTexture.SaveAsPng(stream, textureWidth, textureHeight); } #endif }
public static void SaveTexture(Texture2D texture, string path) { if (texture != null) texture.SaveAsPng(new FileStream(path, FileMode.Create), texture.Width, texture.Height); }
public static void UpdateTile(Texture2D texture) { const int TextureSize = 173; const string FilePath = "/Shared/ShellContent/LiveTile.jpg"; // Save texture to isolated storage IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication(); using (IsolatedStorageFileStream stream = isolatedStorage.CreateFile(FilePath)) { texture.SaveAsPng(stream, TextureSize, TextureSize); } // Update the tile ShellTile tile = ApplicationInfo.ApplicationLiveTile; if (tile != null) { tile.Update(new StandardTileData() { BackgroundImage = new Uri("isostore:" + FilePath, UriKind.Absolute), }); } }
public void screenshot() { count += 1; DateTime debugDate = DateTime.Now; string filename = debugDate.Year + "" + debugDate.Month + "" + debugDate.Day + "." + debugDate.Hour + "" + debugDate.Minute + "" + debugDate.Second + "."; filename += count.ToString(); int w = GraphicsDevice.PresentationParameters.BackBufferWidth; int h = GraphicsDevice.PresentationParameters.BackBufferHeight; //force a frame to be drawn (otherwise back buffer is empty) Draw(new GameTime()); //pull the picture from the buffer int[] backBuffer = new int[w * h]; GraphicsDevice.GetBackBufferData(backBuffer); //copy into a texture Texture2D texture = new Texture2D(GraphicsDevice, w, h, false, GraphicsDevice.PresentationParameters.BackBufferFormat); texture.SetData(backBuffer); //save to disk Stream stream = File.OpenWrite(filename + ".png"); texture.SaveAsPng(stream, w, h); stream.Dispose(); texture.Dispose(); }
public static void Screenshot(GraphicsDevice device) { byte[] screenData; screenData = new byte[device.PresentationParameters.BackBufferWidth * device.PresentationParameters.BackBufferHeight * 4]; device.GetBackBufferData<byte>(screenData); Texture2D t2d = new Texture2D(device, device.PresentationParameters.BackBufferWidth, device.PresentationParameters.BackBufferHeight, false, device.PresentationParameters.BackBufferFormat); t2d.SetData<byte>(screenData); int i = 0; string name = "ScreenShot" + i.ToString() + ".png"; while (File.Exists(name)) { i += 1; name = "ScreenShot" + i.ToString() + ".png"; } Stream st = new FileStream(name, FileMode.Create); t2d.SaveAsPng(st, t2d.Width, t2d.Height); st.Close(); t2d.Dispose(); }
public static void Save(this Texture2D target, string path) { using (var stream = System.IO.File.OpenWrite(path)) target.SaveAsPng(stream, target.Bounds.Width, target.Bounds.Height); }
/// <summary> /// Loads the resources from any other XNA game like if they were form this one and extracts them. /// Tested with the XNA resources from the games "Terraria" and "Stardew Valley" with success. /// With applications like "ILSpy" you can see the source code from XNA games since they are .NET. /// The idea of this application is to find secrets hidden in the game textures and resources, /// but it should never be used to do anything illegal, so be sure you have the proper /// permissions before you start using it on random games. Jupisoft will never be responsible. /// </summary> protected override void LoadContent() { try { try { if (!Directory.Exists(Program.Ruta_XNA)) { Directory.CreateDirectory(Program.Ruta_XNA); } } catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } List <string> Lista_Rutas = new List <string>(); List <string> Lista_Rutas_XSB = new List <string>(); string[] Matriz_Rutas = Directory.GetFiles(Program.Ruta_XNA, "*.xnb", SearchOption.AllDirectories); if (Matriz_Rutas != null && Matriz_Rutas.Length > 0) { Lista_Rutas.AddRange(Matriz_Rutas); Matriz_Rutas = null; } Matriz_Rutas = Directory.GetFiles(Program.Ruta_XNA, "*.xwb", SearchOption.AllDirectories); if (Matriz_Rutas != null && Matriz_Rutas.Length > 0) { Lista_Rutas.AddRange(Matriz_Rutas); Matriz_Rutas = null; } Matriz_Rutas = Directory.GetFiles(Program.Ruta_XNA, "*.xgs", SearchOption.AllDirectories); if (Matriz_Rutas != null && Matriz_Rutas.Length > 0) { Lista_Rutas.AddRange(Matriz_Rutas); Matriz_Rutas = null; } Matriz_Rutas = Directory.GetFiles(Program.Ruta_XNA, "*.xsb", SearchOption.AllDirectories); if (Matriz_Rutas != null && Matriz_Rutas.Length > 0) { //Lista_Rutas.AddRange(Matriz_Rutas); Lista_Rutas_XSB.AddRange(Matriz_Rutas); if (Lista_Rutas_XSB.Count > 1) { Lista_Rutas.Sort(); } Matriz_Rutas = null; } if (Lista_Rutas.Count > 1) { Lista_Rutas.Sort(); } Matriz_Rutas = Lista_Rutas.ToArray(); Lista_Rutas = null; if (Matriz_Rutas != null && Matriz_Rutas.Length > 0) // There are files to extract. { foreach (string Ruta in Matriz_Rutas) { try { if (!string.IsNullOrEmpty(Ruta) && File.Exists(Ruta)) { string Ruta_Relativa = '.' + Ruta.Substring(Program.Ruta_Aplicación.Length).Substring(0, (Ruta.Length - Program.Ruta_Aplicación.Length) - 4); string Ruta_Salida = Ruta.Substring(0, Ruta.Length - 4); try // Try to read as a 2D texture and export as a PNG image. { Microsoft.Xna.Framework.Graphics.Texture2D Textura = base.Content.Load <Texture2D>(Ruta_Relativa); if (Textura != null) { MemoryStream Lector_Memoria = new MemoryStream(); int Ancho = 16; // Default on error. int Alto = 16; try { Ancho = Textura.Width; } catch { Ancho = 16; } try { Alto = Textura.Height; } catch { Alto = 16; } Textura.SaveAsPng(Lector_Memoria, Ancho, Textura.Height); byte[] Matriz_Bytes = Lector_Memoria.ToArray(); Lector_Memoria.Close(); Lector_Memoria.Dispose(); Lector_Memoria = null; Lector_Memoria = new MemoryStream(Matriz_Bytes); Image Imagen_Original = null; try { Imagen_Original = Image.FromStream(Lector_Memoria, false, false); } catch { Imagen_Original = null; } Lector_Memoria.Close(); Lector_Memoria.Dispose(); Lector_Memoria = null; Matriz_Bytes = null; if (Imagen_Original != null) // Reconvert the image to 24 or 32 bits with alpha. { //Ancho = Imagen_Original.Width; // Could the width or height change? //Alto = Imagen_Original.Height; Bitmap Imagen = new Bitmap(Ancho, Alto, !Image.IsAlphaPixelFormat(Imagen_Original.PixelFormat) ? PixelFormat.Format24bppRgb : PixelFormat.Format32bppArgb); Graphics Pintar = Graphics.FromImage(Imagen); Pintar.CompositingMode = CompositingMode.SourceCopy; Pintar.CompositingQuality = CompositingQuality.HighQuality; Pintar.InterpolationMode = InterpolationMode.HighQualityBicubic; Pintar.PixelOffsetMode = PixelOffsetMode.HighQuality; Pintar.SmoothingMode = SmoothingMode.None; Pintar.TextRenderingHint = TextRenderingHint.AntiAlias; Pintar.DrawImage(Imagen_Original, new System.Drawing.Rectangle(0, 0, Ancho, Alto), new System.Drawing.Rectangle(0, 0, Ancho, Alto), GraphicsUnit.Pixel); Pintar.Dispose(); Pintar = null; while (File.Exists(Ruta_Salida + ".png")) { Ruta_Salida += '_'; } Imagen.Save(Ruta_Salida + ".png", ImageFormat.Png); Ruta_Salida = null; Imagen.Dispose(); Imagen = null; Imagen_Original.Dispose(); Imagen_Original = null; Ruta_Relativa = null; Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. continue; // Go to the next XNB resource file. } } } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } try // Try to read as a string and string dictionary and export as Unicode text. { Dictionary <string, string> Diccionario = base.Content.Load <Dictionary <string, string> >(Ruta_Relativa); if (Diccionario != null && Diccionario.Count > 0) { while (File.Exists(Ruta_Salida + ".txt")) { Ruta_Salida += '_'; } FileStream Lector = new FileStream(Ruta_Salida + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); Lector.SetLength(0L); Lector.Seek(0L, SeekOrigin.Begin); StreamWriter Lector_Texto = new StreamWriter(Lector, Encoding.Unicode); foreach (KeyValuePair <string, string> Entrada in Diccionario) { try { Lector_Texto.WriteLine(Entrada.Key); Lector_Texto.WriteLine(Entrada.Value); Lector_Texto.WriteLine(); Lector_Texto.Flush(); } catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); continue; } } Lector_Texto.Close(); Lector_Texto.Dispose(); Lector_Texto = null; Lector.Close(); Lector.Dispose(); Lector = null; Diccionario = null; Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. continue; // Go to the next XNB resource file. } } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } try // Try to read as an int and text dictionary and export as Unicode text. { Dictionary <int, string> Diccionario = base.Content.Load <Dictionary <int, string> >(Ruta_Relativa); if (Diccionario != null && Diccionario.Count > 0) { while (File.Exists(Ruta_Salida + ".txt")) { Ruta_Salida += '_'; } FileStream Lector = new FileStream(Ruta_Salida + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); Lector.SetLength(0L); Lector.Seek(0L, SeekOrigin.Begin); StreamWriter Lector_Texto = new StreamWriter(Lector, Encoding.Unicode); foreach (KeyValuePair <int, string> Entrada in Diccionario) { try { Lector_Texto.WriteLine(Entrada.Key.ToString()); Lector_Texto.WriteLine(Entrada.Value); Lector_Texto.WriteLine(); Lector_Texto.Flush(); } catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); continue; } } Lector_Texto.Close(); Lector_Texto.Dispose(); Lector_Texto = null; Lector.Close(); Lector.Dispose(); Lector = null; Diccionario = null; Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. continue; // Go to the next XNB resource file. } } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } try // Try to read as an int and int array dictionary and export as Unicode text. { Dictionary <int, int[]> Diccionario = base.Content.Load <Dictionary <int, int[]> >(Ruta_Relativa); if (Diccionario != null && Diccionario.Count > 0) { while (File.Exists(Ruta_Salida + ".txt")) { Ruta_Salida += '_'; } FileStream Lector = new FileStream(Ruta_Salida + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); Lector.SetLength(0L); Lector.Seek(0L, SeekOrigin.Begin); StreamWriter Lector_Texto = new StreamWriter(Lector, Encoding.Unicode); // .Default? foreach (KeyValuePair <int, int[]> Entrada in Diccionario) { try { Lector_Texto.WriteLine(Entrada.Key.ToString()); if (Entrada.Value != null && Entrada.Value.Length > 0) { for (int Índice = 0; Índice < Entrada.Value.Length; Índice++) { try { Lector_Texto.Write(Entrada.Value[Índice].ToString() + (Índice + 1 < Entrada.Value.Length ? ", " : null)); } catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); continue; } } Lector_Texto.WriteLine(); } else { Lector_Texto.WriteLine(); } Lector_Texto.WriteLine(); Lector_Texto.Flush(); } catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); continue; } } Lector_Texto.Close(); Lector_Texto.Dispose(); Lector_Texto = null; Lector.Close(); Lector.Dispose(); Lector = null; Diccionario = null; Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. continue; // Go to the next XNB resource file. } } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } try // Try to read as a sprite font and export as a PNG image. { Microsoft.Xna.Framework.Graphics.SpriteFont Fuente = base.Content.Load <SpriteFont>(Ruta_Relativa); if (Fuente != null) { Fuente = null; while (File.Exists(Ruta_Salida + ".png")) { Ruta_Salida += '_'; } if (XNA_Extractor.Extract.XnbExtractor.Extract(Ruta, Ruta_Salida + ".png", false, false, false, true)) { Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. continue; // Go to the next XNB resource file. } } } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } try // Try to read as a sound effect and export as WAV audio file. { Microsoft.Xna.Framework.Audio.SoundEffect Efecto_Sonido = base.Content.Load <Microsoft.Xna.Framework.Audio.SoundEffect>(Ruta_Relativa); if (Efecto_Sonido != null) { Efecto_Sonido.Dispose(); Efecto_Sonido = null; while (File.Exists(Ruta_Salida + ".wav")) { Ruta_Salida += '_'; } if (XNA_Extractor.Extract.XnbExtractor.Extract(Ruta, Ruta_Salida + ".wav", false, false, true, false)) { //Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. continue; // Go to the next XNB resource file. } } } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } /*try // Try to read as an effect and export as ?. * { * Microsoft.Xna.Framework.Graphics.Effect Efecto = base.Content.Load<Effect>(Ruta_Relativa); * if (Efecto != null) * { * Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. * continue; // Go to the next XNB resource file. * } * } * catch (Exception Excepción) * { * //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); * }*/ try // Try to read as a multiple type and export as a PNG image. { while (File.Exists(Ruta_Salida + ".png")) { Ruta_Salida += '_'; } if (XNA_Extractor.Extract.XnbExtractor.Extract(Ruta, Ruta_Salida + ".png", false, true, true, true)) { Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. continue; // Go to the next XNB resource file. } } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } try // Try to read as a bank wave file and export as multiple WAV sound files. { //while (File.Exists(Ruta_Salida + ".wav")) Ruta_Salida += '_'; //MessageBox.Show(Path.GetDirectoryName(Ruta_Salida), Ruta_Salida); if (/*string.Compare(Path.GetExtension(Ruta), ".xwb", true) == 0 && */ XNA_Extractor.Extract.XactExtractor.Extract(Ruta, Path.GetDirectoryName(Ruta))) { Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. continue; // Go to the next XNB resource file. } } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } // TODO: Add support for more resource types... } } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); continue; } } Matriz_Rutas = null; } // This works perfectly, but the class from "XactExtractor.cs" seems to export too many files? if (Lista_Rutas_XSB != null && Lista_Rutas_XSB.Count > 0) // Post-process the track names if present. { List <char> Lista_Caracteres_Inválidos = new List <char>(Path.GetInvalidFileNameChars()); foreach (string Ruta in Lista_Rutas_XSB) { try { FileStream Lector_Entrada = new FileStream(Ruta, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite); if (Lector_Entrada.Length > 0L) // Not empty. { byte[] Matriz_Bytes = new byte[Lector_Entrada.Length]; // Read the whole file at once. int Longitud = Lector_Entrada.Read(Matriz_Bytes, 0, Matriz_Bytes.Length); Lector_Entrada.Close(); Lector_Entrada.Dispose(); Lector_Entrada = null; if (Longitud < Matriz_Bytes.Length) { Array.Resize(ref Matriz_Bytes, Longitud); } string Ruta_Actual = Path.GetDirectoryName(Ruta); int Total_Pistas = 0; for (int Índice = 1; Índice < int.MaxValue; Índice++) { if (File.Exists(Ruta_Actual + "\\" + Índice.ToString() + " Unknown.wav")) { Total_Pistas++; } else { break; // Stop when a track in order is missing. } } List <string> Lista_Nombres = new List <string>(); int Índice_Anterior = Matriz_Bytes.Length - 1; // This byte should be zero (string ender). for (int Índice = Matriz_Bytes.Length - 2; Índice >= 0; Índice--) { if (Matriz_Bytes[Índice] == 0) { if (Índice + 1 != Índice_Anterior) // Avoid multiple nulls. { string Nombre = null; for (int Índice_Caracter = Índice + 1; Índice_Caracter < Índice_Anterior; Índice_Caracter++) { char Caracter = (char)Matriz_Bytes[Índice_Caracter]; if (!char.IsControl(Caracter) && Caracter != 'ÿ' && !Lista_Caracteres_Inválidos.Contains(Caracter)) { Nombre += Caracter; } } if (string.IsNullOrEmpty(Nombre)) { Nombre = "Unknown"; } Lista_Nombres.Add(Nombre); //if (Lista_Nombres.Count >= Total_Pistas) break; } Índice_Anterior = Índice; } } if (Lista_Nombres != null && Lista_Nombres.Count > 0) { for (int Índice_Pista = Total_Pistas, Índice_Nombre = 0; Índice_Pista >= 1; Índice_Pista--, Índice_Nombre++) { try { File.Move(Ruta_Actual + "\\" + Índice_Pista.ToString() + " Unknown.wav", Ruta_Actual + "\\" + Índice_Pista.ToString() + " " + Lista_Nombres[Índice_Nombre] + ".wav"); } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); continue; } } Lista_Nombres.Reverse(); string Ruta_Salida = Ruta.Substring(0, Ruta.Length - 4); while (File.Exists(Ruta_Salida + ".txt")) { Ruta_Salida += '_'; } FileStream Lector = new FileStream(Ruta_Salida + ".txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); Lector.SetLength(0L); Lector.Seek(0L, SeekOrigin.Begin); StreamWriter Lector_Texto = new StreamWriter(Lector, Encoding.Unicode); foreach (string Nombre in Lista_Nombres) { try { Lector_Texto.WriteLine(Nombre); Lector_Texto.Flush(); } catch (Exception Excepción) { //Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); continue; } } Lector_Texto.Close(); Lector_Texto.Dispose(); Lector_Texto = null; Lector.Close(); Lector.Dispose(); Lector = null; Lista_Nombres = null; Program.Eliminar_Archivo_Carpeta(Ruta); // Delete the copied XNB resource. continue; // Go to the next XNB resource file. } } } catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); continue; } } Lista_Caracteres_Inválidos = null; } Depurador.Detener_Depurador(); this.Exit(); } catch (Exception Excepción) { Depurador.Escribir_Excepción(Excepción != null ? Excepción.ToString() : null); } }