1
votes

I have a texture that I use as a screenshot of the screen. When I save the texture as a png file it seems perfect, but I also want to show the captured image on the screen. So I converted the Texture to Sprite but for some reason, the final result sprite is just a random image of another UI image that I have on the screen and not of the texture that I saved to a png file which is correct.

Here is my code:

        var tex = new Texture2D(recwidth, recheight, TextureFormat.RGB24, false);
        Rect rex = new Rect(startX, startY, (float)recwidth, (float)recheight);
        WaitForEndOfFrame frameEnd = new WaitForEndOfFrame();
        tex.ReadPixels(rex, rdPXX, rdPXY);
        tex.Apply();

        // Encode texture into PNG
        var bytes = tex.EncodeToPNG();
        Sprite sprite = new Sprite();
        sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width / 2, tex.height / 2));
        image.GetComponent<Image>().overrideSprite = sprite;
        Destroy(tex);
2

2 Answers

2
votes

Don’t destroy the texture. The Sprite always needs a texture reference. The Sprite object keeps only metadata about the texture like a pivot or UVs (position and size in a sprite atlas)

2
votes

Just create the sprite directly using Sprite.Create() with arguments. Unity is now deprictaed default constructor of Create(). also Don't destroy the texture.

Try this one,

        var tex = new Texture2D(recwidth, recheight, TextureFormat.RGB24, false);
        Rect rex = new Rect(startX, startY, (float)recwidth, (float)recheight);
        WaitForEndOfFrame frameEnd = new WaitForEndOfFrame();
        tex.ReadPixels(rex, rdPXX, rdPXY);
        tex.Apply();

        // Encode texture into PNG
        var bytes = tex.EncodeToPNG();
        Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width / 2, tex.height / 2));
        image.GetComponent<Image>().overrideSprite = sprite;