- Home /
Converting transparent Texture2D to Sprite
I'm creating a Texture2D by snapshotting an object with a camera. Here is the gist of what I do: (The class is big, so this is just an extract to show the important parts.)
_renderTexture = new RenderTexture(64, 64, 10, RenderTextureFormat.ARGB32);
_camera.targetTexture = _renderTexture;
RenderTexture.active = _renderTexture;
Texture2D tex = new Texture2D(_renderTexture.width, _renderTexture.height);
var texture2D = tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
tex.Apply();
This works fine and I have verified it by applying the resulting Texture2D to a cube and it shows the texture on the cube. So then I try to convert the image to a sprite:
var sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), new Vector2(0.5f, 0.5f));_
This gives me a blank sprite (seen as transparent in the Unity editor). Applying the sprite to any UI.Image will make the image transparent. Manually applying any other sprite to the same image shows the sprite as expected.
I have noticed that when I use Texture2D.EncodeToPNG the image produced can only be seen by a few applications. For example Windows Explorer will show the icon (thumb view), but Windows Photo Viewer, Paint and Paint.Net will show the same image as a transparent image (correct image dimensions, but nothing visible). VLC however will show the image correctly.
So I'm thinking that the image has some properties that makes it transparent and that's why the sprite becomes transparent.
So my question is how do I properly convert a transparent Texture2D into a Sprite?
The transparency can be a cutout, fading is not necessary - so if required a workaround with some temp background color can be used.
EDIT: Alpha (transparency) is definitively the problem. I added a repaint without alpha before tex.Apply(); and the image shows up in the sprite as expected. This causes me to loose transparency. I will (temporarily) solve that by using a specific background color which I replace with transparency, though this is not the best way to go.
// Between ReadPixels and Apply:
for (int x = 0; x < tex.width; x++)
{
for (int y = 0; y < tex.height; y++)
{
var color = tex.GetPixel(x, y);
tex.SetPixel(x, y, new Color(color.r, color.g, color.b));
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613175508im_/https://answers.unity.com/themes/thub/images/avi.jpg)