如何将texture2D保存为jpeg文件

本文关键字:jpeg 文件 保存 texture2D | 更新日期: 2023-09-27 17:50:14

我试图在一个纹理上绘制许多纹理来创建RTS游戏的地图,虽然我可以在屏幕上绘制单个纹理,但将它们全部绘制到渲染目标似乎没有效果(调试时窗口仍然是AliceBlue)。我试图确定是否有任何东西被绘制到渲染目标,所以我试图将其保存为Jpeg文件,然后从我的桌面查看Jpeg。我如何从MemoryStream访问Jpeg ?

protected override 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();
    }

如何将texture2D保存为jpeg文件

我做了一个简单的截图方法,

  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); ?看起来……不要那样做!这将导致巨大的延迟,加载数百个贴图,每秒数百次!在你的LoadContent()方法中创建一个全局纹理Texture2D DirtDextureDirtTexture = Content.Load<Texture2D>(t.texture); ,现在当你绘制时,你可以使用spriteBatch.Draw(DirtTexture,...

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

你不需要每帧都新建RenderTarget和Spritebatch !只需在Initialize()方法中执行即可!

也请参阅RenderTarget2D和XNA RenderTarget Sample获取有关使用渲染目标的更多信息

编辑:我意识到这一切都在LoadContent,我没有看到,因为格式混乱,记得在你的绘制方法中添加Foreach (Tile等)