Unity 移动平台拍照截屏并保存到相册

Unity 移动平台拍照截屏并保存到相册

@(Unity3D)[客户端业务功能]

在实习期间碰到需要实现一个调用手机摄像机拍照 并截图 同时将图片保存到相册的功能,并且需要在IOS和Android平台上都能运行,由于这种和操作系统平台进行交互的功能要是自己实现的话就得敲原生接口了,好在Unity平台的生态非常好,而且Unity 开发团队也为跨平台作了不少工作,所以我选择用插件和Unity 提供的接口实现这个需求!


文章目录

    • Unity 移动平台拍照截屏并保存到相册
      • 相关插件和Unity 脚本API
      • 代码块
    • 结果演示

相关插件和Unity 脚本API

  • UnityNativeGallery 用于保存图片到手机相册
  • WebCamTexture 用于调用手机摄像头

代码块


/*
核心业务逻辑代码,部分来自网络。仅供记录和参考
*/
    /// 
    /// 调用设备摄像头拍照
    /// 
    /// 
    public IEnumerator Photograph()
    {
#if UNITY_IPHONE || UNITY_ANDROID
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            Debug.Log("---has camera authorization---");
            if (webCamTexture != null&&webCamTexture.isPlaying) webCamTexture.Stop();
            int camNum = WebCamTexture.devices.Length;
            if (camNum < 1) yield return null;
            string backCamName = WebCamTexture.devices[camNum - 1].name;
            for (int i = 0; i < camNum; i++)
                if (!WebCamTexture.devices[i].isFrontFacing)
                {
                    backCamName = WebCamTexture.devices[i].name;
                    Debug.Log("---backCamName---");
                }                   
            webCamTexture = new WebCamTexture(backCamName, Screen.width, Screen.height, 30);
            webCamTexture.wrapMode = TextureWrapMode.Repeat;
            rawImage.texture = webCamTexture;
            webCamTexture.Play();
            Debug.Log("---has playing---");
        }
        
#endif

#if UNITY_STANDALONE_WIN||UNITY_EDITOR
        Debug.LogError("try to photograph in a PC");
        yield return null;
#endif
    }


    /// 
    /// 选取图片,移动平台打开相册选取
    /// 
    /// 
    /// 
    /// 
    public void PickImage(int maxSize, Action OnLoadSucceed, Action OnLoadFailed)
    {
#if UNITY_IPHONE || UNITY_ANDROID
        NativeGallery.Permission permission = NativeGallery.GetImageFromGallery((path) =>
        {
            Debug.Log("---Image path: " + path);
            if (path == null) return;
            rawImage.texture = NativeGallery.LoadImageAtPath(path, maxSize);
        }, "Select a PNG image", "image/png", maxSize);

        if (permission > 0) OnLoadSucceed();
        else OnLoadFailed();
   }
#endif

    /// 
    /// 截图,Windows使用Unity场景截图,移动端调用原生接口截图!
    /// 
    public void Capture()
    {
#if UNITY_IPHONE || UNITY_ANDROID
        Texture2D texture2D = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
        texture2D.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
        texture2D.Apply();
        string filename = string.Format("{0:yyyyMMddHHmmssffff}.png", DateTime.Now);
        NativeGallery.SaveImageToGallery(texture2D, "test", filename);
        Destroy(texture2D);
#endif
#if UNITY_STANDALONE_WIN
        Camera camera3d = GameObject.Find("3DCamera").GetComponent<Camera>();
        Rect rect = new Rect(Vector2.zero, new Vector2(Screen.width, Screen.height));
        RenderTexture rt = new RenderTexture((int) Screen.width, (int) rect.height, 24);
        camera3d.targetTexture = rt;
        camera3d.Render();
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int) rect.width, (int) rect.height, TextureFormat.RGBA32, false);
        screenShot.ReadPixels(rect, 0, 0);
        screenShot.Apply();
        camera3d.targetTexture = null;
        RenderTexture.active = null;
        GameObject.Destroy(rt);
        string filepath = "C:\\Desstop";//路径请自拟,这里随便写的
        byte[] bytes = screenShot.EncodeToPNG();
        System.IO.File.WriteAllBytes(filepath, bytes);
#endif
       Debug.log("已保存到相册(手机)或目标位置(电脑)");
    }

结果演示

  • 真机测试不便演示,代码仅作为记录或参考

你可能感兴趣的:(Unity,引擎)