teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

別解決方法のソース追加

2015/09/29 07:16

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -97,4 +97,201 @@
97
97
  ```
98
98
  一応これで動くようにはなりました.
99
99
  ただ稀にこの待機処理を通しても正しく読み込まれない( 又は完全にファイルクローズする前にアクセスしている? )事があるらしく挙動がおかしくなることがあります.
100
- なのでもう少し何かしらの解決策が無いか調べてみようと思います.
100
+ なのでもう少し何かしらの解決策が無いか調べてみようと思います.
101
+
102
+
103
+ 今のところCaptureScreenshot()のデータ書き込みを検知する方法が見つからないのでsho_csさんの回答の別の取り方を参考にソースを組み直しました.
104
+ コルーチン内で1ピクセルずつデータを取り出しTexture2Dにしてそれをコールバックで返してから別スレッドでそのファイルを保存することで安定して動かすことが出来ました.
105
+ 別スレッドではなくコルーチン内で画像を作成しているのはUnityのクラスはどうやら別スレッドから操作できないらしくメインスレッド内で画像を作成する必要が出てきたからです.
106
+
107
+ タイトルとは違う解決方法になりましたが今回はこの方法で解決ということにしました.
108
+ ```C#
109
+ using UnityEngine;
110
+ using System.Collections;
111
+ using System.IO;
112
+ using System.Collections.Generic;
113
+ using System;
114
+ using System.Threading; // スレッド使用.
115
+
116
+
117
+ // スクリーンショット撮影クラス.
118
+ // 現在PC上ではできるがAndroidではうまく動かない.
119
+ // スクリーンショットの撮影時点でエラーが発生する.
120
+ public class ScreenCapture{
121
+
122
+
123
+ //--- クラス宣言 ---
124
+ private class CaptureInfo{
125
+
126
+ private string path;
127
+ private string id;
128
+ private bool isFinished;
129
+ private Texture2D tex;
130
+
131
+ public string Path { get{ return this.path; } }
132
+ public string Id { get{ return this.id; } }
133
+ public bool IsFinished { get{ return this.isFinished; } }
134
+ public Texture2D Tex { get{ return this.tex; } }
135
+
136
+ public CaptureInfo(
137
+ string path,
138
+ string id,
139
+ Texture2D tex ){
140
+ this.path = path;
141
+ this.id = id;
142
+ this.tex = tex;
143
+ this.isFinished = false;
144
+ }
145
+
146
+ public void finish(){
147
+ this.isFinished = true;
148
+ }
149
+
150
+ }
151
+
152
+
153
+ //--- 定数 ---
154
+ private const string PICTURE_EXTENSION = ".png";
155
+
156
+ //--- 変数&プロパティ ---
157
+ public delegate void CallBackTex2D( Texture2D tex, string filePath ); // コールバック( Texture2D ver ).
158
+ public delegate void CallBackSprite( Sprite spr, string filePath ); // コールバック( Sprite ver ).
159
+ private Dictionary< string, CaptureInfo > captureList; // キャプチャ情報リスト.
160
+
161
+
162
+ //--- メソッド ---
163
+
164
+ public ScreenCapture(){
165
+
166
+ this.captureList = new Dictionary< string, CaptureInfo >();
167
+ }
168
+
169
+
170
+
171
+ // スクリーンショットを撮影し,コールバックでTexture2Dとファイルパスを返す.
172
+ public void captureScreenshot(
173
+ MonoBehaviour mono,
174
+ CallBackTex2D callback,
175
+ string fileName,
176
+ string folderPath = "",
177
+ bool isOverWrite = false ){
178
+
179
+ mono.StartCoroutine( captureScreenshotCor( callback, fileName, folderPath, isOverWrite ) );
180
+ }
181
+ private IEnumerator captureScreenshotCor(
182
+ CallBackTex2D callback,
183
+ string fileName,
184
+ string folderName,
185
+ bool isOverWrite ){
186
+
187
+ #if !UNITY_EDITOR && UNITY_ANDROID
188
+ // 出力パス( 指定したフォルダが無ければ作成 ).
189
+ folderName = ( folderName != "" ) ? folderName + "/" : Application.productName + "Images/";
190
+ {
191
+ string folderPath = Application.persistentDataPath + "/" + folderName;
192
+ if ( !Directory.Exists( folderPath ) ){
193
+ Directory.CreateDirectory( folderPath );
194
+ }
195
+ }
196
+
197
+ fileName += PICTURE_EXTENSION;
198
+ string filePath = Application.persistentDataPath + "/" + folderName + fileName; // 最終的な保存先.
199
+
200
+ yield return new WaitForEndOfFrame();
201
+
202
+ // 撮影.
203
+ Texture2D tex = new Texture2D( Screen.width, Screen.height, TextureFormat.ARGB32, false );
204
+ tex.ReadPixels( new Rect( 0, 0, Screen.width, Screen.height ), 0, 0, false );
205
+ tex.Apply();
206
+
207
+ // キャプチャ用の情報を作成.
208
+ string captureID = this.getNowTimeString();
209
+ CaptureInfo info = new CaptureInfo( filePath, captureID, tex );
210
+ this.captureList.Add( captureID, info );
211
+
212
+ // コールバックでスプライトを先に渡す.
213
+ callback( tex, filePath );
214
+
215
+ // 別スレッドを作成しそっちで保存.
216
+ Thread thread = new Thread( new ParameterizedThreadStart( this.saveCaptureImage ) );
217
+ thread.Start( captureID );
218
+ while ( !this.captureList[ captureID ].IsFinished ){
219
+ yield return new WaitForSeconds( 0 );
220
+ }
221
+ #endif
222
+
223
+ yield return new WaitForEndOfFrame();
224
+ }
225
+
226
+
227
+
228
+ // 指定したパスのバイナリデータをbyte型配列で返す.
229
+ private byte[] readBinary(
230
+ string path ){
231
+
232
+ byte[] bytes = ( File.Exists( path ) ) ? File.ReadAllBytes( path ) : null;
233
+ if ( bytes == null )
234
+ Debug.LogError( "ファイルが存在しません." );
235
+ return bytes;
236
+ }
237
+
238
+
239
+ // 指定したパス,サイズのTexture2Dを作成し,返す.
240
+ private Texture2D readTexture2D(
241
+ string path,
242
+ int width,
243
+ int height ){
244
+
245
+ byte[] data = this.readBinary( path );
246
+ Texture2D tex = new Texture2D( width, height );
247
+ tex.LoadImage( data );
248
+
249
+ return tex;
250
+ }
251
+
252
+
253
+ // 指定したパス,サイズのスプライトを作成し,返す.
254
+ private Sprite readSprite(
255
+ string path,
256
+ int width,
257
+ int height ){
258
+
259
+ Texture2D tex = this.readTexture2D( path, width, height );
260
+ Sprite spr = Sprite.Create( tex, new Rect( 0, 0, width, height ), Vector2.zero );
261
+
262
+ return spr;
263
+ }
264
+
265
+
266
+
267
+ // 現在時刻のストリングを取得.
268
+ // フォーマット : YY-MM-DD-OO-MM-SS.
269
+ private string getNowTimeString(){
270
+
271
+ string ret = DateTime.Now.Year.ToString() + "-";
272
+ ret += DateTime.Now.Month.ToString() + "-";
273
+ ret += DateTime.Now.Day.ToString() + "-";
274
+ ret += DateTime.Now.Hour.ToString() + "-";
275
+ ret += DateTime.Now.Minute.ToString() + "-";
276
+ ret += DateTime.Now.Second.ToString();
277
+ return ret;
278
+ }
279
+
280
+
281
+
282
+ // 指定されたIDの画像を保存( 別スレッドで起動 ).
283
+ private void saveCaptureImage(
284
+ object id ){
285
+
286
+ string captureID = ( string )id;
287
+ CaptureInfo info = this.captureList[ captureID ];
288
+
289
+
290
+ // 画像を保存.
291
+ byte[] byteData = this.captureList[ captureID ].Tex.EncodeToPNG();
292
+ File.WriteAllBytes( this.captureList[ captureID ].Path, byteData );
293
+ this.captureList[ captureID ].finish();
294
+ }
295
+
296
+ }
297
+ ```

1

参考サイトをもとに書き直したソースの追加.

2015/09/29 07:16

投稿

退会済みユーザー
title CHANGED
File without changes
body CHANGED
@@ -36,4 +36,65 @@
36
36
 
37
37
  このCaptureScreenshot()の終了を検知する方法あるいはファイルの書き込みの完了を検知する方法はあるのでしょうか?
38
38
  又それらの方法が無い場合の代替案としてはどのようなものが有るのでしょうか?
39
- よろしくお願いします.
39
+ よろしくお願いします.
40
+
41
+
42
+ **sho_csさんの紹介した参考ページの情報をもとにプログラム組み直してみました.**
43
+ 待機する処理は指定のファイルが有るか否か,そのファイルを開くことができるかどうかで二重にチェックをかけ.
44
+ ファイルが存在していてファイルへのアクセスができない間は待機する...というようにしました.
45
+ ```lang-C#
46
+ private IEnumerator captureScreenshotCor(
47
+ CallBackSprite callback,
48
+ string fileName,
49
+ string folderName,
50
+ bool fileOverWrite ){
51
+
52
+
53
+ // 出力パス( 指定したフォルダが無ければ作成 ).
54
+ folderName = ( folderName != "" ) ? folderName + "/" : Application.productName + "Images/";
55
+ {
56
+ string folderPath = Application.persistentDataPath + "/" + folderName;
57
+ if ( !Directory.Exists( folderPath ) ){
58
+ Directory.CreateDirectory( folderPath );
59
+ }
60
+ }
61
+
62
+ fileName += PICTURE_EXTENSION;
63
+ Application.CaptureScreenshot( folderName + fileName );
64
+ string filePath = Application.persistentDataPath + "/" + folderName + fileName; // 最終的な保存先.
65
+
66
+ // ファイルが存在していて且つアクセス可能になったらファイルの保存処理が終了している.
67
+ bool isFileComplete = false;
68
+ while ( !isFileComplete ){
69
+
70
+ Debug.Log( "Saving !! " );
71
+ yield return new WaitForEndOfFrame();
72
+
73
+ bool isFileExists = File.Exists( filePath );
74
+ bool isFileLocked = false;;
75
+ FileStream stream = null;
76
+ try{
77
+ stream = new FileStream( filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None );
78
+ }catch{
79
+ Debug.Log( "ファイルがロックされているか又は開けない." );
80
+ isFileLocked = true;
81
+ }finally{
82
+ if ( stream != null )
83
+ stream.Close();
84
+ }
85
+
86
+
87
+ isFileComplete = ( isFileExists == true && isFileLocked != true ) ? true : false;
88
+ }
89
+
90
+
91
+ // コールバック用スプライト作成及びコールバク呼び出し.
92
+ Sprite spr = this.readSprite( filePath, Screen.width, Screen.height );
93
+ callback( spr, filePath );
94
+
95
+ yield return null;
96
+ }
97
+ ```
98
+ 一応これで動くようにはなりました.
99
+ ただ稀にこの待機処理を通しても正しく読み込まれない( 又は完全にファイルクローズする前にアクセスしている? )事があるらしく挙動がおかしくなることがあります.
100
+ なのでもう少し何かしらの解決策が無いか調べてみようと思います.