How to resize and save Texture2D in XNA?

In the level editor, which I made for my XNA game (the editor is also in XNA), I enable scaling Texture2D objects.

When a user tries to save a level, I would like to resize the image file on disk so that it does not require scaling in the game.

Is there an easy way to create an image file (preferred PNG) from a scaled Texture2D object?

+5
source share
4 answers

You can scale your textures by rendering to the render target with the desired size, and then save the rendering texture.

, . GraphicsDevice, . . , ( ).

using System;
using System.Runtime.InteropServices;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

class Program
{
    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern IntPtr GetConsoleWindow();

    static void Main(string[] args)
    {
        string sourceImagePath = args[0];
        string destinationImagePath = args[1];
        int desiredWidth = int.Parse(args[2]);
        int desiredHeight = int.Parse(args[3]);

        GraphicsDevice graphicsDevice = new GraphicsDevice(
            GraphicsAdapter.DefaultAdapter,
            DeviceType.Hardware,
            GetConsoleWindow(),
            new PresentationParameters());
        SpriteBatch batch = new SpriteBatch(graphicsDevice);

        Texture2D sourceImage = Texture2D.FromFile(
            graphicsDevice, sourceImagePath);

        RenderTarget2D renderTarget = new RenderTarget2D(
            graphicsDevice, 
            desiredWidth, desiredHeight, 1, 
            SurfaceFormat.Color);

        Rectangle destinationRectangle = new Rectangle(
            0, 0, desiredWidth, desiredHeight);

        graphicsDevice.SetRenderTarget(0, renderTarget);

        batch.Begin();
        batch.Draw(sourceImage, destinationRectangle, Color.White);
        batch.End();

        graphicsDevice.SetRenderTarget(0, null);

        Texture2D scaledImage = renderTarget.GetTexture();
        scaledImage.Save(destinationImagePath, ImageFileFormat.Png);
    }
}
+11
0

, , , , .

, Zune, , , , , , .

, XNA, WinForms Image , .

BMP PNG, , Texture2D.Save(), , Image.

Image. http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/6fe3d353-0b09-440b-95c9-701efdc9e20a/

0

I have code that makes a larger / smaller copy of the texture, but after a while I get errors. After 30 resizing, I get the exception not the first time.

There seems to be a problem with rendertarget, but I'm not sure. I wonder if you will get these exceptions if you run this code too?

0
source

All Articles