1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Unity] 画面をキャプチャしてバイナリで保存する

Last updated at Posted at 2020-04-21

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フレーム遅れた画像が書き出されてしまうので気を付けること。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?