Retrieving screenshot with Application.persistentDataPath (C#, IOS)

I am taking a screenshot and saving it to the gallery like this:

screenShotPNG = screenShot.EncodeToPNG();
screenshotpath = Application.persistentDataPath + “/” + “photoName.png”
System.IO.File.WriteAllBytes(screenshotpath, screenShotPNG);

The photo is saving fine, I can open up the photo gallery on IOS and look at it, but later in the code I want to retrieve it to display it in my applications local gallery. I’m using the following code, but nothing is displaying. Am I missing something obvious? Do I need to add additional specifications to the path?

GUI.Button( new Rect(0,0, Screen.width,Screen.height), “”, Application.persistentDataPath + “/” + “photoName.png” );

Thanks,
Jacob

You cannot load an image into the button that way.

Here is a quick and very dirty way to load the image, however it requires you to know the size of the image.

using System.IO;
using UnityEngine;

public class RenderButtonWithImageFromPath : MonoBehaviour
{
	private void OnGUI()
	{
		var fileName = Application.persistentDataPath + "/" + "photoName.png";
		var bytes = File.ReadAllBytes( fileName );
		var texture = new Texture2D( 73, 73 );
		texture.LoadImage( bytes );
		GUI.Button( new Rect( 0, 0, 800, 100 ), texture );
	}
}

If you are going to use this code I suggest that you cache the texture in a variable instead of loading it in OnGUI everytime.

3 Likes

One more thing for anyone with too much time to spend. Use Path.Combine instead of concatenating the path yourself. It will take care of slashes pointing in the right direction depending on which system you’re running on.

var fileName = Path.Combine( Application.persistentDataPath, "photoName.png" );
2 Likes

Just what I was looking for, thanks :slight_smile: I’m guessing that because the image is a screenshot the image dimensions will be the resolution of the device, right?

Sounds like a fair assumption. You might have a challenge with portrait/landscape modes or if the user is allowed to synchronize the images to other devices. If you have some spare time, take a look at the PNG header, it is probably very simple to read the width and height from the byte array.

You can use BitConverter.ToInt32 on the byte array to read an int if you know the position within the array.

1 Like