ソースに絡まるエスカルゴ

貧弱プログラマの外部記憶装置です。

【Unity】備忘録#4 画像読み込みについて

前回でファイルアクセスが出来るようになったので、今回は画像読み込みについてになります。
rikoubou.hatenablog.com

手順としては以下の通りになります。

1:対象の画像ファイルをバイナリとして読み込む
2:読み込んだバイナリをTextureにする

■1:対象の画像ファイルをバイナリとして読み込む
FileStreamで読み込み、バイナリに変換してその値を返します。

public byte[] readPngFile(string path) {
	using (FileStream fileStream = new FileStream (path, FileMode.Open, FileAccess.Read)) {
		BinaryReader bin = new BinaryReader (fileStream);
		byte[] values = bin.ReadBytes ((int)bin.BaseStream.Length);
		bin.Close ();
		return values;
	}
}

■2:読み込んだバイナリをTextureにする
1のreadPngFileで取得したバイナリをTextureに変換します。

public Texture readByBinary(byte[] bytes) {
	Texture2D texture = new Texture2D (1, 1);
	texture.LoadImage (bytes);
	return texture;
}

new Texture2D (1, 1)の引数はそれぞれ縦横の画像サイズなのですが、
LoadImageでバイトを読み込むと元の画像サイズになるので問題はありません。


2でTextureにした後は前に書いた記事のように設定すれば表示されます。
rikoubou.hatenablog.com


これで外部にある画像ファイルをスクリプトで読み込み、Unity内で扱うことができます。