Skip to content

Instantly share code, notes, and snippets.

@naojitaniguchi
Created October 21, 2015 10:50
Show Gist options
  • Save naojitaniguchi/17f1f9358b4f5331d732 to your computer and use it in GitHub Desktop.
Save naojitaniguchi/17f1f9358b4f5331d732 to your computer and use it in GitHub Desktop.
Get Pixel data from Render Texture and save Pixel data to .png file in button call back . Unity5
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;
public class SaveRenderTextureButton : MonoBehaviour {
public Camera targetCamera;
public string saveFileName;
private Texture2D targetTexture;
// Use this for initialization
void Start () {
Button button = this.GetComponent<Button>();
button.onClick.AddListener(onClicked);
}
// Update is called once per frame
void Update () {
}
void saveTextureToFile()
{
byte[] b = targetTexture.EncodeToPNG();
File.WriteAllBytes(saveFileName, b);
}
protected virtual void onClicked()
{
Debug.Log("onClicked");
Debug.Log("width + " + targetCamera.targetTexture.width );
Debug.Log("height + " + targetCamera.targetTexture.height);
targetTexture = new Texture2D(targetCamera.targetTexture.width, targetCamera.targetTexture.height, TextureFormat.ARGB32, false);
RenderTexture.active = targetCamera.targetTexture;
targetTexture.ReadPixels(new Rect(0, 0, targetCamera.targetTexture.width, targetCamera.targetTexture.height), 0, 0);
targetTexture.Apply();
RenderTexture.active = null; // added to avoid errors
saveTextureToFile();
Debug.Log("saved");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment