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


'유니티' 카테고리의 다른 글

유니티 Screen Orientation  (0) 2018.09.04
World Position to the specific Rect screen position  (0) 2018.09.03
Unity Attitude  (0) 2018.09.03
유니티 FrameRate 확인  (0) 2018.06.26
유니티 화면 꺼짐 방지  (0) 2018.06.26
Posted by ssume
,