[SOLVED] SaveAsJpeg not Writing to the File

I am creating a level editor for my game that exports an image file, with each pixel representing a specific tile. I am creating this map as a Texture2D using the SetData function. I can display this texture on the screen, but when I try to save it using the SaveAsJpeg function, I just get an empty file. I can export all of my sprite sheets that were imported from the content folder without issue. Is there something that I need to do to that Texture2D before I can export it? (I am creating my game using the UWP option).

This is how I am generating the Texture2D.

`public void GenerateImage()
var colorData = new Color[30 * 17];
levelTex = new Texture2D(graphicsDevice, 30, 17);
for (int yPos = 0; yPos <= 29; yPos++)
for (int xPos = 0; xPos <= 16; xPos++)
colorData[(yPos * 17) + xPos] = new Color(100 + yPos, 200-xPos, 250);
levelTex.SetData(colorData,0, 30*17);``


This is how I am generating the file.

public void ExportLevel()
            string pathName = Windows.Storage.KnownFolders.SavedPictures.Path;
               System.IO.Directory.CreateDirectory(pathName + "/Hand Cannon Janky Reality Exported Levels");
               System.IO.Stream myFile = System.IO.File.Create(pathName + "/Hand Cannon Janky Reality Exported Levels/" + "FileName.png");
               levelTex.SaveAsJpeg(myFile, levelTex.Width, levelTex.Height);
            catch (UnauthorizedAccessException exception)
                System.Diagnostics.Debug.WriteLine("Cannot Save " + exception.Message);

What version of MonoGame do you use?

Please wrap your System.IO.File.Create in a using. Sometimes it not creates the file, if you miss it.

First If you are not using a using statement you must close the file.
Send your folder name is way to long and has spaces. Depending on platform this can cause issues and is generally not a good idea.
Third I’m not sure if directory.creat will throw an error when the directory already exists.

Now I can’t really see anything else.
Have you put a breakpoint at leveltex.saveasjpg to make sure it’s ok?

Hope this helps

Closing the file fixed the issue. I also added the using statement and changed the path name for extra measure. Thanks for the help everyone.

1 Like