開発入門 > Unity > UnityでRenderTextureをファイルに保存

UnityでRenderTextureをファイルに保存

忘備録

RenderTextureをpng形式で保存します。適当なからオブジェクトにスクリプトを貼り付け、保存したいRenderTextureを指定。1フレームごとに記録されます。

SaveRenderTextureToPng.cs

using UnityEngine;
using System.Collections;
using System.IO;

public class SaveRenderTextureToPng : MonoBehaviour {

    public RenderTexture RenderTextureRef;

    // Use this for initialization
    void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
        savePng();
    }

    void savePng()
    {

        Texture2D tex = new Texture2D(RenderTextureRef.width, RenderTextureRef.height, TextureFormat.RGB24, false);
        RenderTexture.active = RenderTextureRef;
        tex.ReadPixels(new Rect(0, 0, RenderTextureRef.width, RenderTextureRef.height), 0, 0);
        tex.Apply();

        // Encode texture into PNG
        byte[] bytes = tex.EncodeToPNG();
        Object.Destroy(tex);

        //Write to a file in the project folder
        File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);

    }


}

 

2017/11/12追記
RenderTextureをJpegに保存したいだけのときはこちらを利用

    /// <summary>
    /// RenderTextureをJPG形式で保存します
    /// </summary>
    /// <param name="RenderTextureRef"></param>
    /// <param name="saveFilePath"></param>
    private void SaveRenderTextureToJpg(RenderTexture RenderTextureRef, string saveFilePath)
    {
        Texture2D tex = new Texture2D(RenderTextureRef.width, RenderTextureRef.height, TextureFormat.RGB24, false);
        RenderTexture.active = RenderTextureRef;
        tex.ReadPixels(new Rect(0, 0, RenderTextureRef.width, RenderTextureRef.height), 0, 0);
        tex.Apply();

        // Encode texture into PNG
        byte[] bytes = tex.EncodeToPNG();
        UnityEngine.Object.Destroy(tex);

        //Write to a file in the project folder
        File.WriteAllBytes(saveFilePath, bytes);
    }

 

 

カテゴリー: Unity

HOME / Coporate Site

© Copyright 2018 STYLY..