Unity 截图优化

代码片段:

    IEnumerator Cut(Camera camera, string path)
    {

        Debug.LogError("!!!!!__________" + System.DateTime.Now.ToString("HH:mm:ss.fff"));
        RenderTexture rt = RenderTexture.GetTemporary(1024, 1024, 32);
        camera.targetTexture = rt;
        byte[] arr = new byte[] { };
        yield return new WaitForEndOfFrame();

        AsyncGPUReadbackRequest request=AsyncGPUReadback.Request(rt, 0, TextureFormat.ARGB32);
        yield return new WaitUntil(()=> {
            if (request.done || request.hasError)
            {
                if (request.hasError)
                {
                    VRDebug.LogError("保存图片失败 GPU readback error detected."+path);
                    return true;
                }
                Debug.LogError("____________________________" + System.DateTime.Now.ToString("HH:mm:ss.fff"));
                var data = request.GetData<byte>();

                System.IntPtr ptr = ToIntPtr(data);//用指针,比copy成byte[],一张1024*1024的图,快了100毫秒
                Texture2D texture2D = new Texture2D(1024, 1024, TextureFormat.ARGB32, false);
                texture2D.LoadRawTextureData(ptr, data.Length);

                //byte[] array = new byte[data.Length];
                //data.CopyTo(array);
                //Texture2D texture2D = new Texture2D(1024, 1024, TextureFormat.ARGB32, false);
                //texture2D.LoadRawTextureData(array);

                byte[] png = ImageConversion.EncodeToPNG(texture2D);
                File.WriteAllBytes(path, png);
                Debug.LogError("____________________________" + System.DateTime.Now.ToString("HH:mm:ss.fff"));
                return true;
            }
            else
            {
                return false;
            }
        });
    }

    /// <summary>
    /// 找到NativeArray<byte>的指针
    /// </summary>
    /// <param name="array"></param>
    /// <returns></returns>
    System.IntPtr ToIntPtr(NativeArray<byte> array)
    {
        unsafe
        {
            return (System.IntPtr)Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.GetUnsafePtr(array); // void* -> IntPtr explicit conversion.
        }
    }

    /// <summary>
    /// 通过指针,转为NativeArray<byte>
    /// </summary>
    /// <param name="ptr"></param>
    /// <param name="length"></param>
    /// <returns></returns>
    NativeArray<byte> ToNativeArray(System.IntPtr ptr,int length)
    {
        unsafe
        {
            return Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>((void*)ptr, length, Allocator.None);

        }
    }

 

posted on 2021-03-05 15:49  Jason_c  阅读(830)  评论(0编辑  收藏  举报