Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- IEnumerator TakeScreenshotAndSaveCoroutine(int width, int height, Camera screenshotCamera, string saveToFileName)
- {
- yield return new WaitForEndOfFrame();
- if (width <= 0 || height <= 0)
- {
- yield return null;
- }
- if (screenshotCamera == null) screenshotCamera = Camera.main;
- Texture2D screenshot = new Texture2D(width, height, TextureFormat.RGB24, false);
- RenderTexture renderTex = new RenderTexture(width, height, 24);
- screenshotCamera.targetTexture = renderTex;
- screenshotCamera.Render();
- RenderTexture.active = renderTex;
- RenderTexture current_tex;
- // Saving by one slice each frame
- screenshot.ReadPixels(new Rect(0, 0, width / 4, height), 0, 0);
- yield return null;
- for (int i = 1; i < 4; i++)
- {
- current_tex = RenderTexture.active;
- RenderTexture.active = renderTex;
- screenshot.ReadPixels(new Rect(width * ((float)i / 4), 0, width * ((float)i / 4), height), (int) (width * ((float)i / 4)), 0);
- RenderTexture.active = current_tex;
- screenshotCamera.targetTexture = null;
- yield return null;
- }
- screenshot.Apply(false);
- screenshotCamera.targetTexture = null;
- RenderTexture.active = null;
- Destroy(renderTex);
- yield return 0;
- if (screenshot != null && saveToFileName != null)
- {
- if (Application.platform == RuntimePlatform.OSXPlayer ||
- Application.platform == RuntimePlatform.WindowsPlayer &&
- Application.platform != RuntimePlatform.LinuxPlayer
- || Application.isEditor)
- {
- byte[] bytes;
- if (saveToFileName.ToLower().EndsWith(".jpg"))
- bytes = screenshot.EncodeToJPG();
- else bytes = screenshot.EncodeToPNG();
- FileStream fs = new FileStream(saveToFileName, FileMode.OpenOrCreate);
- BinaryWriter w = new BinaryWriter(fs);
- w.Write(bytes);
- w.Close();
- fs.Close();
- }
- }
- yield return screenshot;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement