0. 概要
Unityで大量のシミュレーション画像を生成してBMPで保存していたが、非常に取り回しが悪いので複数画像をバイナリ化して1つのファイルにしたい。そこで、PostRender
を使って描画される画面の左上ピクセルから順にRGBで並んだ配列をバイナリ化して1つのファイルに保存したので、その備忘録を以下に記す。
1. バイナリ画像化
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Capture : MonoBehaviour {
Texture2D capture_display;
string fileName = "screenshot\\image.bin";
System.IO.BinaryWriter writer;
byte[] yxrgb;
int ary_size;
// Use this for initialization
void Start () {
capture_display = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
writer = new System.IO.BinaryWriter(new System.IO.FileStream(fileName, System.IO.FileMode.Append));
ary_size = Screen.width * Screen.height * 3;
yxrgb = new byte[ary_size];
}
private void OnDestroy()
{
writer.Close();
}
private IEnumerator OnPostRender() {
yield return new WaitForEndOfFrame();
// capture the frame
RenderTexture.active = Camera.main.targetTexture;
capture_display.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
capture_display.Apply();
for (int i = 0; i < Screen.width; i++)
{
for (int j = 0; j < Screen.height; j++)
{
int offset = ( (i * Screen.height) + (j) ) * 3;
yxrgb[offset + 0] = (byte)((int)(capture_display.GetPixel(i, j).r * 255));
yxrgb[offset + 1] = (byte)((int)(capture_display.GetPixel(i, j).g * 255));
yxrgb[offset + 2] = (byte)((int)(capture_display.GetPixel(i, j).b * 255));
}
}
writer.Write(yxrgb);
}
}
yield return new WaitForEndOfFrame();
を入れておかないと1フレーム遅れた画像が書き出されてしまうので気を付けること。