Created
January 20, 2020 17:27
-
-
Save Santarh/899ed0914cf7c4517bdb36233be66c19 to your computer and use it in GitHub Desktop.
[Unity] Get PNG bytes from RenderTexture with Color Conversion.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!