- Home /
ReadPixels works on device (iPad) but not in the editor?
the following code, when run on iPad, works and saves the images I expect to see
void OnPostRender ()
{
//save image from unity for testing. The camera that renders is called explicitely using Camera.Render
Texture2D texture = new Texture2D(_renderSize,_renderSize,TextureFormat.ARGB32,false);
//setting a test color to see if saving works correctly and if ReadPixels changes the color
Color32[] colors = new Color32[_renderSize*_renderSize];
for(int i=0; i<_renderSize*_renderSize; i++){
colors[i] = new Color32(0,127,0,255);
}
texture.SetPixels32(colors);
texture.ReadPixels(new Rect(0,0,_renderSize,_renderSize),0,0);
texture.Apply();
byte[] bytes = texture.EncodeToPNG();
System.String path = Application.dataPath.Substring(0,Application.dataPath.LastIndexOf('/'));
path = path.Substring(0,path.LastIndexOf('/')) + "/Documents/UnityImage"+_count.ToString ()+".png";
Debug.Log("Unity: saving image to "+path);
System.IO.File.WriteAllBytes(path, bytes);
}
when running it in the editor though, the images saved to disk are pure green (0,127,0,255), meaning that ReadPixels seems to do nothing. I'm not getting any error - any idea what could cause this behaviour?
note: I explicitely want to read from the framebuffer and not use a renderTexture. This is because I use the framebuffer to pass some procedural renderings to the XCode project which reads it from the frameBuffer. The above code is intended for debugging when run in the editor - but unfortunately it does not work in the editor, which means I need to test each change on the device
Answer by Bessu · Dec 02, 2015 at 12:12 PM
To my experience it's impossible to trust ReadPixels on the editor. For example ReadPixels in my code on windows works perfect on editor but not on a device with the same resolution. Or the same code won't work on mac editor but still works on ipad with the same resolution as the editor.
Answer by leo-dom · Jul 22, 2013 at 08:31 AM
Call texture.Apply() before ReadPixels().
Maybe Apply() will apply the cached SetPixels32() changes, so it will override the ReadPixels().
And it is a implementation-relate problem, the best practice is call Apply just after SetPixels calls.
PS: This is just my guess, because your code does work in My Unity Editor.
Answer by wibble82 · Dec 02, 2015 at 12:42 PM
I would hazard a guess that you are calling 'read pixels' before calling 'apply'.
Until you have called 'apply', the effects of any pixel setting are not written to the texture. Exactly where they're stored temporarily will depend on the platform implementation.
I suspect you are seeing a difference in the undefined behaviour of 'what happens if I read pixels before calling apply'.
The fix is probably to simply ensure your texture changes have been applied before trying to read it.