Search code examples
c#androidimageunity-game-enginetexture2d

printing a texture2D to file or as image for debugging purposes


I am trying to figure out how an image is processed (what it looks like, etc...) at several stages of Image Processing operations, so I have written the following co-routine to capture a screenshot, but I am not sure how to print out the taken shots at different stages (for example as png images)

public void CaptureFrame(RectTransform rect)
{
    StartCoroutine( Co_Capture(rect) );
}

private IEnumerator Co_Capture(RectTransform rect)
{
    yield return new WaitForEndOfFrame();

    _texture = new Texture2D( (int)rect.sizeDelta.x, (int)rect.sizeDelta.y );
    _texture.ReadPixels( new Rect( rect.anchoredPosition.x - (rect.sizeDelta.x * 0.5f), rect.anchoredPosition.y - (rect.sizeDelta.y * 0.5f), rect.sizeDelta.x, rect.sizeDelta.y ), 0, 0 );
    _texture.Apply();

    OnImageCaptured( new ScreenShotEventArgs(_texture) );
}

Given that I build the app to an Android device, ideally I would like to have the images saved both in a folder somewhere (through Unity3D Editor) as well as on the device in its data folder, for example. Something akin to Debug.Log messages that you print out at different stages to see which parts of your code are reached, etc...

What options do I have? What is the code/command/method for saving an image/picture through Unity3D and also on an Android tablet, so that the developer can see the images at various stages or processing?


Solution

  • You got some of it right in the comment section. You use EncodeToPNG() to convert it to a byte array then save it with File.WriteAllBytes. What you didn't get right is the path.

    You use save to Application.persistentDataPath if you want that to work on Android, iOS and any platform. It is a must to save it in a folder instead of directly saving it to Application.persistentDataPath.

    So that should be Application.persistentDataPath+"/yourfoldername/imagename.png".

    Again, this: Application.persistentDataPath+"/imagename.png" will fail on iOS because you are trying to write directly to the sandbox which requires a folder like I mentioned above.

    Finally, I noticed you are using + to concatenate paths. Avoid doing that and instead use Path.Combine.

    string tempPath = Path.Combine(Application.persistentDataPath, "yourfoldername");
    tempPath = Path.Combine(tempPath, "yourfoldername.png");