- Home /
Texture2D saves as PNG correctly but doesn't display properly in RawImage
I have a small bit of code i uses to perform a screen capture of my main camera. Here's most of the code i have in my ScreenshotManager on my main camera:
private Camera m_camera;
private bool m_takeScreenshotOnNextFrame = false;
[SerializeField]
private RawImage m_image;
private void OnPostRender()
{
if (m_takeScreenshotOnNextFrame)
{
m_takeScreenshotOnNextFrame = false;
RenderTexture renderTexture = m_camera.targetTexture;
Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.ARGB32, false);
Rect rect = new Rect(0, 0, renderTexture.width, renderTexture.height);
renderResult.ReadPixels(rect, 0, 0);
byte[] byteArray = renderResult.EncodeToPNG();
System.IO.File.WriteAllBytes(Application.dataPath + "/TestScreen.png", byteArray);
Debug.Log("Saved Screen.");
m_image.texture = renderResult;
RenderTexture.ReleaseTemporary(renderTexture);
m_camera.targetTexture = null;
m_camera.cullingMask = m_camera.cullingMask | (1 << LayerMask.NameToLayer("UI"));
m_camera.fieldOfView = 60.0f;
}
}
private void TakeScreenshot(int width, int height)
{
m_camera.targetTexture = RenderTexture.GetTemporary(width, height, 16);
m_takeScreenshotOnNextFrame = true;
m_camera.cullingMask = m_camera.cullingMask & ~(1 << LayerMask.NameToLayer("UI"));
m_camera.fieldOfView = 50.0f;
}
This code works fine for exporting the screenshot as a PNG, but i can't get it to work for displaying the texture on the UI with m_image. I've tried with RawImage and UIImage (with Sprite.Create) and both give me the same result: the image gets slightly, uniformly grey when i take the screenshot.
Here's how my RawImage is set up, if that can help:
Any hint or advice on how i could get this to work is appreciated.
Answer by FlorentAlbyon · Jul 29, 2020 at 12:36 PM
Found the issue. For anyone who'd stumble upon this problem, you need to call
renderResult.Apply();
On your Texture2D before sending it to the RawImage or creating the sprite with Sprite.Create. This will apply all the modification you've done to your texture.
Your answer
![](https://koobas.hobune.stream/wayback/20220613004254im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Best way to capture super large screenshot images (all GPUs) 0 Answers
Texture2D.EncodeToPng() saves gray PNG, all texture data missing 1 Answer
Taking Non Power of Two Resolution Screen Shots 0 Answers
What am I missing? Saving EXR results in a properly sized blank/transparent EXR Image file. 0 Answers
RenderTexture to Texture2D 4 Answers