유니티

Unity Texture to Texture 2d (convert through RenderTexture)

ssume 2018. 9. 11. 13:13

Convert Texture to Texture2D using RenderTexture

+ Save Texture2D File (EncodeToPNG())


++) in case using casting::

Texture2D test = (Texture2D)targetTexture;

-> creates UnityException: Texture 'textureName' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings.


However, it cannot be saved and an error popped up.

-> Unsupported texture format - Texture2D::EncodeTo functions do not support compressed texture formats.



PROBLEM with source underneath:: Graphics.Blit has transparency problem in Android. -> Maybe it's of Hardware.


-> SOLVED: Use Camera with material and RenderTexture, and use the method Texture2D.ReadPixels. (180912)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Texture targetTexture;
string saveImagePath;
 
private void Save()
{
    int width = targetTexture.width;
    int height = targetTexture.height;
    //save the active render texture
    RenderTexture curRenderTexture = RenderTexture.active;
    
    //create new render texture and copy from the target texture
    RenderTexture copiedRenderTexture = new RenderTexture(width, height, 0);
    Graphics.Blit(targetTexture, copiedRenderTexture);
 
    //change active render texture
    RenderTexture.active = copiedRenderTexture;
 
    //copy to texture 2d
    Texture2D convertedImage = new Texture2D(width, height, TextureFormat.RGBA32, false);
    convertedImage.ReadPixels(new Rect(00, width, height), 00);
    convertedImage.Apply();
 
    //change back to prev active render texture
    RenderTexture.active = curRenderTexture;
 
    //additional
    //save to persistent data path
    Color[] pixels = convertedImage.GetPixels();
    byte[] imgBytes = convertedImage.EncodeToPNG();
    File.WriteAllBytes(saveImagePath, imgBytes);
}
cs