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);
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)