unity 截屏png保存並提取應用

 

using UnityEngine;
using System.Collections;

public delegate void CallBack();//利用委託回調可以先關閉UI,截取到沒有UI的畫面
/// <summary>
/// 截圖工具類
/// </summary>
public class ScreenTool
{
    private static ScreenTool _instance;
    public static ScreenTool Instance
    {
        get
        {
            if (_instance == null)
                _instance = new ScreenTool();
            return _instance;
        }
    }

    /// <summary>
    /// UnityEngine自帶截屏Api,只能截全屏
    /// </summary>
    /// <param name="fileName">文件名</param>
    public void ScreenShotFile(string fileName)
    {
        UnityEngine.ScreenCapture.CaptureScreenshot(fileName);//截圖並保存截圖文件
        Debug.Log(string.Format("截取了一張圖片: {0}", fileName));

#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();//刷新Unity的資產目錄
#endif
    }
    /// <summary>
    /// UnityEngine自帶截屏Api,只能截全屏
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <param name="callBack">截圖完成回調</param>
    /// <returns>協程</returns>
    public IEnumerator ScreenShotTex(string fileName, CallBack callBack = null)
    {
        yield return new WaitForEndOfFrame();//等到幀結束,不然會報錯
        Texture2D tex = UnityEngine.ScreenCapture.CaptureScreenshotAsTexture();//截圖返回Texture2D對象
        byte[] bytes = tex.EncodeToPNG();//將紋理數據,轉化成一個png圖片
        System.IO.File.WriteAllBytes(fileName, bytes);//寫入數據
        Debug.Log(string.Format("截取了一張圖片: {0}", fileName));

        callBack?.Invoke();
#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();//刷新Unity的資產目錄
#endif
    }
    /// <summary>
    /// 截取遊戲屏幕內的像素
    /// </summary>
    /// <param name="rect">截取區域:屏幕左下角爲0點</param>
    /// <param name="fileName">文件名</param>
    /// <param name="callBack">截圖完成回調</param>
    /// <returns></returns>
    public IEnumerator ScreenCapture(Rect rect, string fileName, CallBack callBack = null)
    {
        yield return new WaitForEndOfFrame();//等到幀結束,不然會報錯
        Texture2D tex = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);//新建一個Texture2D對象
        tex.ReadPixels(rect, 0, 0);//讀取像素,屏幕左下角爲0點
        tex.Apply();//保存像素信息

        byte[] bytes = tex.EncodeToPNG();//將紋理數據,轉化成一個png圖片
        System.IO.File.WriteAllBytes(fileName, bytes);//寫入數據
        Debug.Log(string.Format("截取了一張圖片: {0}", fileName));

        callBack?.Invoke();
#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();//刷新Unity的資產目錄
#endif
    }
    /// <summary>
    /// 對相機拍攝區域進行截圖,如果需要多個相機,可類比添加,可截取多個相機的疊加畫面
    /// </summary>
    /// <param name="camera">待截圖的相機</param>
    /// <param name="width">截取的圖片寬度</param>
    /// <param name="height">截取的圖片高度</param>
    /// <param name="fileName">文件名</param>
    /// <returns>返回Texture2D對象</returns>
    public Texture2D CameraCapture(Camera camera, Rect rect, string fileName)
    {
        RenderTexture render = new RenderTexture((int)rect.width, (int)rect.height, -1);//創建一個RenderTexture對象 

        camera.gameObject.SetActive(true);//啓用截圖相機
        camera.targetTexture = render;//設置截圖相機的targetTexture爲render
        camera.Render();//手動開啓截圖相機的渲染

       

        RenderTexture.active = render;//激活RenderTexture
        Texture2D tex = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.ARGB32, false);//新建一個Texture2D對象
        tex.ReadPixels(rect,0, 0);//讀取像素
        tex.Apply();//保存像素信息

      

        camera.targetTexture = null;//重置截圖相機的targetTexture
        RenderTexture.active = null;//關閉RenderTexture的激活狀態
        Object.Destroy(render);//刪除RenderTexture對象

        byte[] bytes = tex.EncodeToPNG();//將紋理數據,轉化成一個png圖片
        System.IO.File.WriteAllBytes(fileName, bytes);//寫入數據
        Debug.Log(string.Format("截取了一張圖片: {0}", fileName));

#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();//刷新Unity的資產目錄
#endif

        return tex;//返回Texture2D對象,方便遊戲內展示和使用
    }
}
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class ScreenShotTest : MonoBehaviour
{
    public Camera renderCamera;
    public GameObject uiCanvas;

    //父物體
    public Transform parent;

    public Scrollbar scrollbar;

    //預製體
    public GameObject obj;
    //截圖命名
    private static int number;
    private void Start()
    {
        LoadTexture2Sprite();
    }

    private void Update()
    {
        //TODO測試
        if (Input.GetKeyUp(KeyCode.Q))
        {
            Debug.Log("自帶截圖1");
            uiCanvas.SetActive(false);
            ScreenTool.Instance.ScreenShotFile(GetFilePath());
        }
        if (Input.GetKeyUp(KeyCode.W))
        {
            Debug.Log("自帶截圖2");
            uiCanvas.SetActive(false);
            StartCoroutine(ScreenTool.Instance.ScreenShotTex(GetFilePath(), Callback));
        }
        if (Input.GetKeyUp(KeyCode.E))
        {
            Debug.Log("普通截圖");
            uiCanvas.SetActive(false);
            StartCoroutine(ScreenTool.Instance.ScreenCapture(new Rect(0, 0, 1920, 1080), GetFilePath(), Callback));
        }
        if (Input.GetKeyUp(KeyCode.R))
        {
            ScreenTool.Instance.CameraCapture(renderCamera, new Rect(0, 0, 512, 512), GetFilePath());
        }

        if (Input.GetMouseButtonDown(2))
        {
            LoadTexture2Sprite();
            for (int i = 0; i < loadsprite.Count; i++)
            {
                GameObject obj_demo = Instantiate(obj, Vector3.zero, Quaternion.identity);
                obj_demo.GetComponent<Image>().sprite = loadsprite[i];
                obj_demo.name = i.ToString();
                obj_demo.transform.SetParent(parent);
               
            }
            parent.GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, loadsprite.Count*205);
            scrollbar.value = 1;
        }
    }

    /// <summary>
    /// 獲取文件完整路徑
    /// </summary>
    /// <returns></returns>
    public string GetFilePath()
    {
        number++;
        return Application.streamingAssetsPath + "/截圖/" + number + ".png";
    }
    public void Callback()
    {
        uiCanvas.SetActive(true);
    }
    //*************************************
    List<Texture2D> loadTexture = new List<Texture2D>();

    List<Sprite> loadsprite = new List<Sprite>();

    private void LoadTexture2Sprite()

    {

        //清空一下,防止爆滿

        loadTexture.Clear();

        loadsprite.Clear();

        //獲取到路勁

        List<string> filePaths = new List<string>();

        filePaths = GetImagePath();

        //新建時要給上大小,小於原先的圖片大小會出現圖片值截取一塊的情況


        //根據讀取到的文件路徑,一個文件一個文件的將圖片存儲進去

        for (int i = 0; i < filePaths.Count; i++)

        {

            Texture2D t2d = new Texture2D(512, 512);

            //根據路勁讀取字節流再轉換成圖片形式

            t2d.LoadImage(getImageByte(filePaths[i]));

            //放到集合裏面

            loadTexture.Add(t2d);

            //將Texture創建成Sprite 參數分別爲圖片源文件,Rect值給出起始點和大小 以及錨點的位置

            Sprite sprite = Sprite.Create(t2d, new Rect(0, 0, t2d.width, t2d.height), Vector2.zero);

            //放入集合

            loadsprite.Add(sprite);
        }
    }

    //根據路徑 將"*.JPG|*.PNG"文件全部加載到集合中
    private List<string> GetImagePath()

    {

        List<string> filePaths = new List<string>();

        string imgtype = "*.JPG|*.PNG";

        string[] ImageType = imgtype.Split('|');

        for (int i = 0; i < ImageType.Length; i++)

        {

            //獲取unity根目錄下的圖片文件夾下的所有文件的路徑 路徑+ 名稱全部存儲在字符串數組中

            string[] dirs = Directory.GetFiles(Application.streamingAssetsPath +"/截圖/", ImageType[i]);

            //

            for (int j = 0; j < dirs.Length; j++)

            {

                filePaths.Add(dirs[j]);

                Debug.Log("圖片路徑爲     " + dirs[j]);

            }

            Debug.Log("一共讀取到" + dirs.Length + "張圖片");

        }



        return filePaths;

    }

    //將“.png|.jpg”轉化成字節
    private static byte[] getImageByte(string imagePath)

    {

        //讀取到文件

        FileStream files = new FileStream(imagePath, FileMode.Open);

        //新建比特流對象

        byte[] imgByte = new byte[files.Length];

        //將文件寫入對應比特流對象

        files.Read(imgByte, 0, imgByte.Length);

        //關閉文件

        files.Close();

        //返回比特流的值

        return imgByte;

    }

}
  

 

 

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