I'm working on a tilesheet builder tool for my game to speed up tile creation, and I need to save a generated texture2D as a png. I've tried using the .SaveAsPng function but it isn't implemented in Monogame.

Is there any way around this in monogame?

EDIT: I've tried this:

private void SaveTextureData(RenderTarget2D texture, string filename)
        byte[] imageData = new byte[4 * texture.Width * texture.Height];

        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(texture.Width, texture.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
        System.Drawing.Imaging.BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, texture.Width, texture.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap.PixelFormat);
        IntPtr pnative = bmData.Scan0;
        System.Runtime.InteropServices.Marshal.Copy(imageData, 0, pnative, 4 * texture.Width * texture.Height);

but it's giving a weird output, and I don't know why: http://i.imgur.com/XT9Dnjj.png

Thanks for any help!

  • \$\begingroup\$ Did you try debugging the issue? Verify your data is accurate, and that your methodology even works with known good data. Worst case scenario you have to write out the data manually. Bitmaps are a simple file format, here is the specification. daubnet.com/en/file-format-bmp \$\endgroup\$
    – Evan
    Jul 28 '14 at 23:01

Your code seems like it would work to me, but there are two things you would need to verify:

  1. Is the render target's format RGBA? Or is it just RGB?
  2. Are you trying to save as a PNG or a BMP? Bitmap.Save() defaults to a BMP image. To save as a PNG, you need to use this overload.

Also, if MonoGame is using the OpenGL renderer, I remember with OpenTK the Bitmap internal format was actually BGRA or something similar (even when specifying PixelFormat.Format32bppArgb), so the byte order may be messed up.

  • \$\begingroup\$ Thanks for the advice, turns out I just messed up the array sorting code, silly error that I didn't catch! \$\endgroup\$
    – user49868
    Jul 29 '14 at 11:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy