簡體   English   中英

如何將Texture2D作為JPEG保存到文件

[英]How to save a texture2D as a jpeg to a file

我試圖在一個紋理上繪制許多紋理以為RTS游戲創建地圖,盡管我可以在屏幕上繪制單個紋理,但是將它們全部繪制到渲染目標似乎沒有效果(調試時窗口仍為AliceBlue )。 我試圖確定是否將任何東西繪制到渲染目標,所以我試圖將其作為Jpeg保存到文件,然后從我的桌面查看該Jpeg。 如何從MemoryStream訪問該Jpeg?

受保護的重寫void LoadContent(){

         spriteBatch = new SpriteBatch(GraphicsDevice);
         gridImage = new RenderTarget2D(GraphicsDevice, 1000, 1000);
         GraphicsDevice.SetRenderTarget(gridImage);
         GraphicsDevice.Clear(Color.AliceBlue);
         spriteBatch.Begin();


         foreach (tile t in grid.tiles)
         {
             Texture2D dirt = Content.Load<Texture2D>(t.texture);
             spriteBatch.Draw(dirt, t.getVector2(), Color.White);
         }
         test = Content.Load<Texture2D>("dirt");


             GraphicsDevice.SetRenderTarget(null);
             MemoryStream memoryStream = new MemoryStream();

            gridImage.SaveAsJpeg(memoryStream, gridImage.Width, gridImage.Height); //Or SaveAsPng( memoryStream, texture.Width, texture.Height )



         //    rt.Dispose();
             spriteBatch.End();
    }

我做了一個簡單的截圖方法,

  void Screenie()
            {
                int width = GraphicsDevice.PresentationParameters.BackBufferWidth;
                int height = 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[width * height];
                GraphicsDevice.GetBackBufferData(backBuffer);

                //Copy to texture
                Texture2D texture = new Texture2D(GraphicsDevice, width, height, false, GraphicsDevice.PresentationParameters.BackBufferFormat);
                texture.SetData(backBuffer);
                //Get a date for file name
                DateTime date = DateTime.Now; //Get the date for the file name
                Stream stream = File.Create(SCREENSHOT FOLDER + date.ToString("MM-dd-yy H;mm;ss") + ".png"); 

                //Save as PNG
                texture.SaveAsPng(stream, width, height);
                stream.Dispose();
                texture.Dispose();
            }

另外,是否正在加載Texture2D dirt = Content.Load<Texture2D>(t.texture); 每幀? 看起來好像...不要那樣做! 這將導致大量的延遲加載數百個瓷磚,每秒數百次! 而是創建一個全局紋理Texture2D DirtDexture並在您的LoadContent()方法中執行DirtTexture = Content.Load<Texture2D>(t.texture); 現在,當您繪制時,您可以執行spriteBatch.Draw(DirtTexture,...

使用spriteBatch = new SpriteBatch(GraphicsDevice); gridImage = new RenderTarget2D(GraphicsDevice, 1000, 1000);

您無需在每個幀上都創建新的RenderTarget和Spritebatch! 只需在Initialize()方法中完成即可!

另請參見RenderTarget2DXNA RenderTarget示例有關使用渲染目標的更多信息。

編輯:我意識到全部在LoadContent中,我沒有看到那是因為格式混亂,請記住在Draw方法中添加您的Foreach(平鋪等)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM