Search Unity

Question how to resolve problem in saving render texture to file as raw bytes?

Discussion in 'General Graphics' started by uc2022, Nov 14, 2022.

  1. uc2022

    uc2022

    Joined:
    May 20, 2022
    Posts:
    6
    I'm trying to save a render texture directly as raw bytes, instead of image, to discard image encoding and thus to speed up the process. However when I read the saved file and re-save it after encoding as PNG, to make sure I did the right thing, I see that PNG file is just blank.
    What am I doing wrong?
    probably irrelevant: project is on HDRP pipeline

    This is the code I'm using to save render texture as raw bytes:
    Code (CSharp):
    1. IEnumerator StartCapture()
    2.         {
    3.             while (true)
    4.             {
    5.                 yield return new WaitForSeconds(0.2f);
    6.                 ScreenCapture.CaptureScreenshotIntoRenderTexture(rt);
    7.                 //compensating for image flip
    8.                 Graphics.Blit(rt, renderTexture, new Vector2(1, -1), new Vector2(0, 1));
    9.  
    10.                if (prevFrame == null)
    11.                 {
    12.                     Setup(targetTextureWidth, targetTextureHeight);
    13.                     Graphics.Blit(renderTexture, prevFrame);
    14.                 }
    15.  
    16.                 flowMaterial.SetTexture("_PrevTex", prevFrame);
    17.  
    18.                 //calculating motion flow frame here
    19.                 Graphics.Blit(renderTexture, flowBuffer, flowMaterial, (int)Pass.Flow);
    20.                 Graphics.Blit(renderTexture, prevFrame);
    21.        
    22.                 AsyncGPUReadback.Request(flowBuffer, 0, TextureFormat.ARGB32, OnCompleteReadbackNew);
    23.             }
    24.  
    25.         }
    26.  
    27.  void OnCompleteReadbackNew(AsyncGPUReadbackRequest request)
    28.         {
    29.             if (request.hasError)
    30.                 return;
    31.  
    32.             var bytes = request.GetData<byte>();
    33.  
    34.             WriteTextureAsyncNew(bytes);
    35.         }
    36.  
    37. async void WriteTextureAsyncNew(NativeArray<byte> bytes)
    38.         {
    39.             imageCount++;
    40.    
    41.             filepathforflow = customOutputFolderPath + imageCount + ".txt";
    42.             await File.WriteAllBytesAsync(filepathforflow, bytes.ToArray());
    43.         }
    This is the code I'm using to read the saved file and re-save it as PNG:
    Code (CSharp):
    1. var newBytes = File.ReadAllBytes(customOutputFolderPath + "5.txt");
    2. var target = new Texture2D(targetTextureWidth, targetTextureHeight, TextureFormat.ARGB32, false);
    3. target.LoadRawTextureData(newBytes);
    4. target.Apply();
    5. var lastBytes = target.EncodeToJPG();
    6. File.WriteAllBytes(customOutputFolderPath + readCount + ".png", lastBytes
     
    Last edited: Nov 14, 2022