获取当前屏幕截图的字符串

20 篇文章 0 订阅
	//获取当前屏幕截图的字符串
    private string GetScreenShotBase64()
    {
        LoadingUI.instance.SetValueAndContent(0f, true);
        Rect camPixelRect = mainCamera.pixelRect;
        // 创建一个RenderTexture对象   
        RenderTexture rt = new RenderTexture((int)camPixelRect.width, (int)camPixelRect.height,0);
        Rect rect = new Rect(0, 0, camPixelRect.width, camPixelRect.height);
        // 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机    
        mainCamera.enabled = false;
        mainCamera.targetTexture = rt;
        //mainCamera.Render();
        mainCamera.clearFlags = CameraClearFlags.SolidColor;
        mainCamera.renderingPath = RenderingPath.DeferredLighting;
        mainCamera.Render();
        mainCamera.clearFlags = CameraClearFlags.Skybox;
        mainCamera.renderingPath = RenderingPath.Forward;
        // 激活这个rt, 并从中中读取像素。    
        RenderTexture.active = rt;
        Texture2D screenShot = new Texture2D((int)camPixelRect.width, (int)camPixelRect.height, TextureFormat.RGB24, false);
        screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素    
        screenShot.Apply();

        byte[] bytes = CommonFunction.ZipTexture2D(screenShot, rect);
        string photoBase64 = Convert.ToBase64String(bytes);
        LoadingUI.instance.SetValueAndContent(0.6f, true);
        // 重置相关参数,以使用camera继续在屏幕上显示    
        mainCamera.targetTexture = null;
        mainCamera.enabled = true;
        RenderTexture.active = null; // JC: added to avoid errors    
        GameObject.Destroy(rt);
        // 最后将这些纹理数据,成一个png图片文件    
        //byte[] bytes = screenShot.EncodeToPNG();
        string filename = Application.dataPath + "/BomScreenshot.png";
#if UNITY_WEBPLAYER
        Debug.Log(filename);
#elif UNITY_STANDALONE_WIN
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张照片: {0}", filename));
#endif
        LoadingUI.instance.SetValueAndContent(1f, false);
        return photoBase64;
    }
    //将截图保存,压缩至1.8M以下
    public static byte[] ZipTexture2D(Texture2D screenShot, Rect capture)
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        long start = GC.GetTotalMemory(true);
        byte[] bytes = screenShot.EncodeToPNG();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        long end = GC.GetTotalMemory(true);
        if ((end - start) >= 1887436)//所占内存是否大于1.8M
        {
            screenShot.Resize((int)(screenShot.width * 0.9f), (int)(screenShot.height * 0.9f), TextureFormat.RGB24, false);
            screenShot.ReadPixels(capture, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素  
            screenShot.Apply();
            return ZipTexture2D(screenShot, capture);
        }

        return bytes;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值