- Home /
EncodeToPNG problem on Android?
I'm trying to capture a screenshot from my application running on Android using the standard code found in some examples:
var width = Screen.width;
var height = Screen.height;
var tex = new Texture2D(width, height, TextureFormat.RGB24, false);
tex.ReadPixels(Rect(0, 0, width, height), 0, 0);
tex.Apply();
var bytes = tex.EncodeToPNG();
Destroy(tex);
File.WriteAllBytes(Application.persistentDataPath + "/screenshot.png", bytes);
The file is created, but for some reason I cannot preview this file in Android. If I open it it shows as a corrupted file (black). I tried in a Galaxy Tab running android 2.2 and an Asus Transformer running 3.2.
If I preview the image from a computer it works. It seems to be a problem with a CRC calculation or bad length. I'm not sure, but the error is something that apparently in Windows is tolerable enough to show the file. Anybody who can help me with this issue?
If you generate the file in the Editor, is it then viewable on Android? i.e. is the problem specific to Android Unity, or to the Android image viewer?
If I generate the file in the Editor and then copy it to Android then it seems to be fine. The problem still occurs when the app is running on the phone and creates the file, it is created "corrupted".
The same phenomenon has happened. It moved normally when returning it to Unity3.3 because it had been generated by Unity3.4. Bug of Unity3.4?
I'm encountering the same issue, and it's definitely a CRC issue. I've called EncodeToPNG() on both the PC and Android, and then opened both resultant PNGs side by side in a hex editor. The only differences are the CRCs.
I filed a bug with Unity. http://fogbugz.unity3d.com/default.asp?421666_cjljpd4n037ipb2t
Can I place a bet on some code making assumptions about the signedness of char...
Answer by Chris 48 · Mar 06, 2012 at 08:47 AM
try ReadPixels on OnPostRender not on Update/LateUpdate.