YAMAのブログ

ほぼ自分用メモです。

【Unity】Android内蔵ストレージにPNGデータを保存する。

Android内蔵ストレージにスクリーンショットを保存するC#スクリプトを作ることに苦戦したのでメモとして残しておきます。

手順1

このstackoverflowのサイトから保存、ロードなどの方法を参考にしました。

stackoverflow.com

保存

string tempPath = Path.Combine(Application.persistentDataPath, "images");
tempPath = Path.Combine(tempPath, "DCUnityOutput.png");
File.WriteAllBytes(tempPath, pngImageByteArray);

tempPathに画像を保存するディレクトリのパスと出力したいPNG画像の名前を代入します。つまり
"temppath = Application.persistentDataPathで作られるパス/images/DCUnityOutput.png"になりますね。

File.WriteAllBytes()を使うことが肝で、この関数を使うためにPNG画像のバイト列が必要になります。

ロード

byte[] pngImageByteArray = null;
string tempPath = Path.Combine(Application.persistentDataPath, "images");
tempPath = Path.Combine(tempPath, "DCUnityOutput.png");
pngImageByteArray = File.ReadAllBytes(tempPath);

byte型でpngImageByteArray を宣言して初期化、画像が保存されているとされるパスをtempPath に代入、File.ReadAllBytes()を使ってbytePNGデータをロードします。

byteデータからPNGデータを作る

Texture2D tempTexture = new Texture2D(2, 2);
tempTexture.LoadImage(pngImageByteArray);

Texture2dのPNGデータをエクスポート/保存

byte[] pngImageByteArray = tempTexture.EncodeToPNG();
string tempPath = Path.Combine(Application.persistentDataPath, "images");
tempPath = Path.Combine(tempPath, "DCUnityOutput.png");
File.WriteAllBytes(tempPath, pngImageByteArray);