Unity获取外置摄像头、原生成像图

获取外置摄像头原生数据

    /// <summary>
    /// 将图片保存在本地
    /// </summary>
    /// <param name="image"></param>
    /// <param name="DownLoadName"> 保存在本地的名字 </param>
    /// <returns></returns>
    IEnumerator DownLoadTexture(Texture2D image, string DownLoadName)
    {
        Texture2D tempImage = null;
        tempImage = image;
        if (tempImage != null)
        {
            byte[] data = tempImage.EncodeToPNG();
            File.WriteAllBytes(Application.streamingAssetsPath + "/" + DownLoadName + ".png", data);
        }

        yield return new WaitForEndOfFrame();

        ServerUse.tmpServerUse.ServerSend();                    //拍完照片以后发送给文哥的客户端
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    /// 
    public GameObject loadScenes;
    IEnumerator Getwindowresult()
    {
        int width = 1080;
        int height = 1920;
        byte[] bytes = GetPhotoPixel(webTex);//资源
        Texture2D texture = new Texture2D(width, height);
        texture.LoadImage(bytes);
        yield return new WaitForSeconds(0.01f);
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
        //img.sprite = sprite;       
        StartCoroutine(DownLoadTexture(texture, "Artwork"));
        yield return new WaitForSeconds(0.01f);
        Resources.UnloadUnusedAssets(); //一定要清理游离资源。
        StopCallCamera();
    }

    /// <summary>
    /// 获取像素
    /// </summary>
    /// <param name="ca"></param>
    /// <returns></returns>
    private byte[] GetPhotoPixel(WebCamTexture ca)
    {
        Texture2D texture = new Texture2D(ca.width, ca.height);
        int y = 0;
        while (y < texture.height)
        {
            int x = 0;
            while (x < texture.width)
            {
                UnityEngine.Color color = ca.GetPixel(x, y);
                texture.SetPixel(x, y, color);
                ++x;
            }
            ++y;
        }
        texture.Apply();
        byte[] pngData = GetJpgData(texture);
        return pngData;
    }

    /// <summary>
    /// 控制拍照
    /// </summary>
    /// <param name="te"></param>
    /// <returns></returns>
    private byte[] GetJpgData(Texture2D te)
    {
        byte[] data = null;
        int quelity = 75;
        while (quelity > 20)
        {
            data = te.EncodeToJPG(quelity);
            int size = data.Length / 1024;
            if (size > 30)
            {
                quelity -= 5;
            }
            else
            {
                break;
            }
        }
        return data;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容