Unity獲取外置攝像頭、原生成像圖

獲取外置攝像頭原生數(shù)據(jù)

    /// <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();                    //拍完照片以后發(fā)送給文哥的客戶端
    }

    /// <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;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容