【Unity】Cameraに写るものをPNGファイルとして保存
2019-12-04
Unityランタイム上でRenderTextureをPNG画像として保存する方法のメモ
Env.
- Unity2019.1.12f1
- Windows10 64bit
Method
Source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.IO; public class CaptureFromCameraSample : MonoBehaviour { [SerializeField] private static readonly string CAPUTURED_PICTURE_SAVE_DIRECTORY = "/"; [SerializeField] private Camera _captureCamera; public IEnumerator Capture() { //_captureCameraに写るものを800*600でPNG画像として保存 var coroutine = StartCoroutine(CaptureFromCamera(800, 600, _captureCamera)); yield return coroutine; } /// <summary> /// CaptureMain /// </summary> /// <param name="width">横解像度</param> /// <param name="height">縦解像度</param> private IEnumerator CaptureFromCamera(int width, int height, Camera camera) { var d_width = camera.targetTexture.width; var d_height = camera.targetTexture.height; Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false); if (camera.targetTexture != null) camera.targetTexture.Release(); camera.targetTexture = new RenderTexture(width, height, 24); yield return new WaitForEndOfFrame(); RenderTexture.active = camera.targetTexture; tex.ReadPixels(new Rect(0, 0, camera.targetTexture.width, camera.targetTexture.height), 0, 0); tex.Apply(); byte[] bytes = tex.EncodeToPNG(); string savePath = Application.streamingAssetsPath + CAPUTURED_PICTURE_SAVE_DIRECTORY + "EXAMPLE_NAME" + ".png"; File.WriteAllBytes(savePath, bytes); Destroy(tex); if (camera.targetTexture != null) camera.targetTexture.Release(); yield break; } } |
Captureを実行することでStreamingAssets内にPng画像として保存される.