Skip to content

Instantly share code, notes, and snippets.

@Santarh
Created January 20, 2020 17:27
Show Gist options
  • Save Santarh/899ed0914cf7c4517bdb36233be66c19 to your computer and use it in GitHub Desktop.
Save Santarh/899ed0914cf7c4517bdb36233be66c19 to your computer and use it in GitHub Desktop.
[Unity] Get PNG bytes from RenderTexture with Color Conversion.
using UnityEngine;
public class SaveTexture : MonoBehaviour
{
private byte[] SaveRenderTextureAsPng(RenderTexture rt)
{
if (rt == null || !rt.IsCreated()) return null;
// Allocate
var sRgbRenderTex = RenderTexture.GetTemporary(rt.width, rt.height, 0, RenderTextureFormat.ARGB32,
RenderTextureReadWrite.sRGB);
var tex = new Texture2D(rt.width, rt.height, TextureFormat.ARGB32, mipChain: false, linear: false);
// Linear to Gamma Conversion
Graphics.Blit(rt, sRgbRenderTex);
// Copy memory from RenderTexture
var tmp = RenderTexture.active;
RenderTexture.active = sRgbRenderTex;
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tex.Apply();
RenderTexture.active = tmp;
// Get PNG bytes
var bytes = tex.EncodeToPNG();
// Destroy
Destroy(tex);
RenderTexture.ReleaseTemporary(sRgbRenderTex);
return bytes;
}
}
@TwinFrame
Copy link

Thank you!

@tomtomtong
Copy link

Good job

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment