1. 程式人生 > >Unity3d 截圖儲存到相簿,並且重新整理相簿

Unity3d 截圖儲存到相簿,並且重新整理相簿

原文連結

using UnityEngine;
using System.Collections;
using System;
using System.IO;

public class CaptureScreenshotMgr: MonoBehaviour
{

    /// <summary>
    /// 儲存截圖圖片,並且重新整理相簿(Android和iOS)
    /// </summary>
    /// <param name="name">若空就按照時間命名</param>
    public void CaptureScreenshot(string name = "")
    {
        string _name = "";
        if (string.IsNullOrEmpty(name))
        {
            _name = "Screenshot_" + GetCurTime() + ".png";
        }
        //編輯器下
        //string path = Application.persistentDataPath + "/" + _name;
        //Application.CaptureScreenshot(path, 0);
        //EDebug.Log("圖片儲存地址" + path);


        //Android版本
        StartCoroutine(CutImage(_name));
        EDebug.Log("圖片儲存地址" + _name);

    }
    //截圖並儲存
    IEnumerator CutImage(string name)
    {
        //圖片大小  
        Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, true);
        yield return new WaitForEndOfFrame();
        tex.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0, true);
        tex.Apply();
        yield return tex;
        byte[] byt = tex.EncodeToPNG();
        string path = Application.persistentDataPath.Substring(0, Application.persistentDataPath.IndexOf("Android"));
        File.WriteAllBytes(path + "/Pictures/Screenshots/" + name, byt);
        string[] paths = new string[1];
        paths[0] = path;
        ScanFile(paths);
    }
    //重新整理圖片,顯示到相簿中
    void ScanFile(string[] path)
    {
        using (AndroidJavaClass PlayerActivity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            AndroidJavaObject playerActivity = PlayerActivity.GetStatic<AndroidJavaObject>("currentActivity");
            using (AndroidJavaObject Conn = new AndroidJavaObject("android.media.MediaScannerConnection", playerActivity, null))
            {
                Conn.CallStatic("scanFile", playerActivity, path, null, null);
            }
        }
    }
    /// <summary>
    /// 獲取當前年月日時分秒,如201803081916
    /// </summary>
    /// <returns></returns>
    string GetCurTime()
    {
        return DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString()
            + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
    }
}