Unity截屏保存到安卓手机相册

1、首先本人同样用了和大家一样的方法在百度查了很久的资料,之后又看API,官方帮助文档,之后终于解决了这个问题。在网上查到的都是代码几乎都是一个模子刻出来的,现在贴上我自己查了资料后改的代码。

2、直接上源码,简单粗暴

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

/// <summary>
/// 截图保存安卓手机相册
/// </summary>
public class CaptureScreenshotMgr : MonoBehaviour
{
    public Text text;
    string _name = "";

    /// <summary>
    /// 保存截屏图片,并且刷新相册 Android
    /// </summary>
    /// <param name="name">若空就按照时间命名</param>
    public void CaptureScreenshot()
    {
        _name = "";
        _name = "Screenshot_" + GetCurTime() + ".png";


#if UNITY_STANDALONE_WIN      //PC平台
       // 编辑器下
       // string path = Application.persistentDataPath + "/" + _name;       
        string path = Application.dataPath + "/" + _name;
        ScreenCapture.CaptureScreenshot(path, 0);
        Debug.Log("图片保存地址" + path);

#elif UNITY_ANDROID     //安卓平台
        //Android版本
        StartCoroutine(CutImage(_name));
        //在手机上显示路径
        // text.text = "图片保存地址" + Application.persistentDataPath.Substring(0, Application.persistentDataPath.IndexOf("Android")) + "/DCIM/Camera/" + _name;
        text.text = "图片保存地址" + Application.persistentDataPath.Substring(0, Application.persistentDataPath.IndexOf("Android")) + "/截屏/" + _name;
#endif
    }
    //截屏并保存
    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 + "/DCIM/Camera/" + name, byt);   //保存到  安卓手机的  DCIM/下的Camera   文件夹下
        File.WriteAllBytes(path + "/截屏/" + 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>
    /// 获取当前年月日时分秒,如20181001444
    /// </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();
    }

}

3、创建 UI界面

场景UI布局
4、之后还要在PlayerSetting中修改Write Permission中的模式为External(SDCard)
在这里插入图片描述

5、ok了 现在导出Apk 在手机上测试吧,截屏之后可以通过文件管理在文件夹中立刻看到,但如果想在相册中看到会有一段延迟。稍等一分钟就可以在相册中看到。

6、拿出我测试已久的 结果图

这个是手机的 文件管理 的 截屏 文件夹中
在这里插入图片描述

这个是手机相册中的截图,等了大概50秒才刷新出来
在这里插入图片描述

好了到现在困扰我几天的难题,今天终于解决了,想用的赶紧测试吧,今天国庆出去溜一圈,嘎嘎嘎····






2021.4.11修改

PlayerSetting中修改Write Permission中的模式为External(SDCard)

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

/// <summary>
/// 截图保存安卓手机相册
/// </summary>
public class CaptureScreenshotMgr : MonoBehaviour
{


    //测试代码空格键截图
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ScreenShootOnClick();
        }
    }

    //截图按钮点击事件
    public void ScreenShootOnClick()
    {

        StartCoroutine(ScreenShoot());
    }


    //图片保存路径
    public string ScreenshotPath()
    {

        string filePath = "";
        switch (Application.platform)
        {
            case RuntimePlatform.WindowsEditor:
                 case RuntimePlatform.OSXEditor:
                filePath = Application.dataPath + "/storage/emulated/0/Camera/";
                break;
            case RuntimePlatform.Android:
                filePath = "/storage/emulated/0/Camera/screenshot/";
                break;
            case RuntimePlatform.IPhonePlayer:
                filePath = Application.persistentDataPath + "/";
                break;
        }
        if (!Directory.Exists(filePath))
        {
            Directory.CreateDirectory(filePath);
        }
        return filePath;
    }
    //截图保存之后刷新相册
    IEnumerator ScreenShoot()
    {
        //图片大小  
        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 fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
        string path = ScreenshotPath() + fileName;
        File.WriteAllBytes(path, byt);
        string[] paths = { path };
        ScanFile(paths);
#if UNITY_EDITOR
        System.Diagnostics.Process.Start(path);
#endif
    }
    //刷新图片,显示到相册中
    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);
            }
        }

    }
}

微信公众号

在这里插入图片描述

  • 7
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值