Azure + Kinect + 保存圖片

參考文檔
[1]https://blog.csdn.net/Wmayy_123/article/details/103681680 Texture2D翻轉
[2]https://passion.blog.csdn.net/article/details/100779131 Texture轉Texture2D
[3]https://blog.csdn.net/hakukou/article/details/104667576 保存Texture2D爲jpg文件

using System.Collections;
using UnityEngine;
using com.rfilkov.kinect;
using System;

public class StorePic : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        KinectManager kinectManager = KinectManager.Instance;
        if (kinectManager != null && kinectManager.IsInitialized())
        {
            Texture texture = KinectManager.Instance.GetColorImageTex(0);

            writeCaptureDataToFile(TextureToTexture2D(texture), "G:\\pic\\", "filename");

        }
    }


    public void writeCaptureDataToFile(Texture2D texture, string dataPath, string filename)
    {
        string path_full = dataPath + filename + ".png";

        // 存入jpg文件
        StartCoroutine(saveTexture2DtoFile(texture, path_full));
    }

    // 保存圖片到指定目錄
    private IEnumerator saveTexture2DtoFile(Texture2D texture, string path, Action<object> callback = null)
    {
        //等待渲染線程結束  
        yield return new WaitForEndOfFrame();

        byte[] textureData = texture.EncodeToPNG();
        System.IO.File.WriteAllBytes(path, textureData);

        callback?.Invoke(null);
        Debug.Log("圖片文件寫入完畢:" + path);
    }

    private Texture2D TextureToTexture2D(Texture texture)
    {
        Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
        RenderTexture currentRT = RenderTexture.active;
        RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
        Graphics.Blit(texture, renderTexture);

        RenderTexture.active = renderTexture;

        texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
        texture2D.Apply();


        RenderTexture.active = currentRT;
        RenderTexture.ReleaseTemporary(renderTexture);



        int width = texture2D.width;//得到圖片的寬度.   
        int height = texture2D.height;//得到圖片的高度 

        Texture2D NewTexture2d = new Texture2D(width, height);//創建一張同等大小的空白圖片 

        int i = 0;

        while (i < height)
        {
            NewTexture2d.SetPixels(0, i, width, 1, texture2D.GetPixels(0, height - i - 1, width, 1));
            i++;
        }
        NewTexture2d.Apply();

        return NewTexture2d;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章