Unity3d獲取外置攝像頭成像、截圖、 上傳服務(wù)器生成二維碼

Capture 截圖工具類

using UnityEngine;
using System.Collections;

 public struct ShotRect
{
    public int w;//width
    public int h;//hight
    public float x;
    public float y;
}

/// <summary>
/// 截屏
/// 注意:須等到當(dāng)前幀結(jié)束后調(diào)用
/// yield return new WaitForEndOfFrame();
/// Capture.ScreenShot();
/// </summary>
public class Capture {

    /// <summary>
    /// 屏幕截屏
    /// </summary>
    public static Texture2D ScreenShot(int width,int height) 
    {
        Texture2D texture = new Texture2D(width, height, TextureFormat.RGB24, false);
        texture.ReadPixels(new Rect(0f, 0f, width,height), 0, 0);//從屏幕的左下角開始讀取一個寬為width,高為height的圖片
        texture.Apply();
        return texture;
    }

    /// <summary>
    /// 相機(jī)截屏
    /// </summary>
    /// <param name="camera">相機(jī)</param>
    /// <param name="width">截圖區(qū)域?qū)?lt;/param>
    /// <param name="height">截圖區(qū)域高</param>
    /// <returns></returns>
    public static Texture2D CameraShot(Camera camera,int width,int height)
    {
        RenderTexture cameraRenderTex = camera.targetTexture;
        RenderTexture renderTex;
        if (cameraRenderTex == null) {
            renderTex = new RenderTexture(Screen.width, Screen.height, 24, RenderTextureFormat.ARGB32);
        }
        else {
            renderTex = new RenderTexture(cameraRenderTex.width, cameraRenderTex.height, cameraRenderTex.depth); 
        }
        Texture2D dest = new Texture2D(width, height, TextureFormat.RGB24, false);
        camera.targetTexture = renderTex;
        camera.Render();
        RenderTexture.active = renderTex;
        dest.ReadPixels(new Rect(0f, 0f, width, height),0, 0);
        dest.Apply();
        RenderTexture.active = null;
        camera.targetTexture = null;
        renderTex.Release();
        return dest;
    }
    /// <summary>
    /// 確定截圖區(qū)域的方法
    /// </summary>
    /// <param name="uicamera"></param>
    /// <param name="a"></param>
    /// <param name="b"></param>
    /// <returns></returns>
    public static ShotRect GetShotArea(Camera uicamera, Transform a, Transform b)
    {
        ShotRect r;
        //轉(zhuǎn)換為屏幕坐標(biāo)
        Vector2 v1 = uicamera.WorldToScreenPoint(a.position);
        Vector2 v2 = uicamera.WorldToScreenPoint(b.position);
        //確定屏幕讀取的起始坐標(biāo)
        r.x = (v1.x > v2.x) ? v2.x : v1.x;
        r.y = (v1.y > v2.y) ? v2.y : v1.y;
        //計(jì)算截圖區(qū)域的寬和高
        r.w = int.Parse(Mathf.Abs(v1.x - v2.x).ToString("F0"));
        r.h = int.Parse(Mathf.Abs(v1.y - v2.y).ToString("F0"));
        return r;
    }

    #region 指定區(qū)域截圖示例
    //IEnumerator Shot()
    //{
    //    ShotRect _rect = Capture.GetShotArea(_camera, p1, p2);
    //    yield return new WaitForEndOfFrame();
    //    Texture2D texture = new Texture2D(_rect.w, _rect.h, TextureFormat.RGB24, false);
    //    texture.ReadPixels(new Rect(_rect.x, _rect.y, _rect.w, _rect.h), 0, 0);
    //    texture.Apply();
    //    _image.texture = texture;
    //} 
    #endregion

}

QR_Code 上傳服務(wù)器生成二維碼類

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine.UI;
using LitJson;
using SimpleJson;
using ZXing;
using ZXing.QrCode;

public class QR_Code : MonoBehaviour
{
    public static QR_Code instance;
    private string Lastresult;
    private Texture defaultQRCodeTexture;
    private void Awake()
    {
        instance = this;
        projectName = Configs.Instance.LoadText("QRCode", "projectName");
        ip = Configs.Instance.LoadText("QRCode", "ip");
        port = Configs.Instance.LoadText("QRCode","port");
    }

    private static Color32[] Encode(string textForEncoding, int width, int height)
    {
        BarcodeWriter writer = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new
            QrCodeEncodingOptions
            {
                Height = height,
                Width = width
            }
        };
        return
        writer.Write(textForEncoding);
    }

    private void ShowSaveInfo(RawImage qrcodeImage)
    {
        string textForEncoding = Lastresult;
        if (textForEncoding != null)
        {
            Texture2D encoded = new Texture2D(256, 256);
            Color32[] color32 = Encode(textForEncoding, encoded.width, encoded.height);
            encoded.SetPixels32(color32);
            encoded.Apply();
            qrcodeImage.texture = encoded;
            Resources.UnloadUnusedAssets();
            GC.Collect();
        }
        else
        {
            qrcodeImage.texture = defaultQRCodeTexture;
        }
    }

    //string url = "http://sq.gzcloudbeingbu.com/Webpage/MyScreenshots.aspx";

    public void UpLoad(byte[] bytes, string timestamp, RawImage qrcodeImage)
    {
        //StartCoroutine(UploadPNG(bytes, timestamp, action));
        StartCoroutine(UpLoadImg(bytes, timestamp, qrcodeImage));
    }

    #region can
    public static JsonObject StringToJsonObj(string str)
    {
        JsonObject player_obj = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(str);
        return player_obj;
    }

    public static JsonArray StringToJsonArr(string str)
    {
        JsonArray player_obj = (JsonArray)SimpleJson.SimpleJson.DeserializeObject(str);
        return player_obj;
    }

    #endregion

    private string projectName = "";
    // string ip = "";
    private string ip = "";
    private string port;

    private IEnumerator UpLoadImg(byte[] bytes, string timestamp, RawImage qrcodeImage)
    {
        string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "/" + timestamp + ".png";
        byte[] bs = bytes;
        WWWForm form = new WWWForm();

        form.AddBinaryData("file", bs, "project:" + projectName + ",file:" + fileName, "image/png");
        WWW www = new WWW("http://" + ip + ":" + port + "/upload/img_upload", form);
        Debug.Log("http://" + ip + ":" + port + "/upload/img_upload");
        Debug.Log(form);
        yield return www;
        if (www.error != null)
        {
            Debug.Log(www.error);
            yield return null;
        }
        else
        {
            JsonObject re = StringToJsonObj(www.text);
            Lastresult = re["url_src"].ToString();
            Debug.Log(Lastresult);
            ShowSaveInfo(qrcodeImage);
            //Debug.Log(re["url_src"].ToString());
            yield return null;
        }

    }
    public static long GetTimeStamp(bool bflag = true)
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        long ret;
        if (bflag)
            ret = Convert.ToInt64(ts.TotalSeconds);
        else
            ret = Convert.ToInt64(ts.TotalMilliseconds);
        return ret;
    }
}

GetCamera 獲取外置攝像頭

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System;

public class GetCamera : MonoBehaviour
{
    public Camera mCamera;
    private WebCamTexture webTex;
    /// <summary>
    /// 攝像機(jī)的圖像數(shù)據(jù) - 進(jìn)行展示
    /// </summary>
    public RawImage cameraImage;

    /************** 截圖操作 *************/
    /// <summary>
    /// 攝像相機(jī)
    /// 倒計(jì)時Image
    /// 倒計(jì)時存儲的圖像
    /// 倒計(jì)時進(jìn)行的延遲的秒數(shù)
    /// 截圖區(qū)域:0 - StartPoint, 1 - EndPoint
    /// 截圖保存圖像
    /// </summary>
    public Camera _camera;
    public Image countDownImage;
    public Sprite[] Countdowns;
    public float timing = 0.2f;
    public Transform[] transforms;
    public RawImage _test;

    /*************** 上傳服務(wù)器 **************/
    /// <summary>
    ///寬,高
    ///開始截圖的位置跟結(jié)束截圖的位置
    ///生成二維碼的RawImage
    /// 截圖區(qū)域:0 - StartPoint, 1 - EndPoint
    /// </summary>
    int width, height;
    Vector3 startPos, endPos;
    public RawImage qr_RawImage;
    public Transform [] qr_transforms;

    private void Start()
    {
        Init();
    }

    private void Update()
    {
        if (Input.GetKeyDown("q"))
        {
            CameraShor();
        }

        if (Input.GetKeyDown("w"))
        {
            BackPhoto();
        }

        if (Input.GetKeyDown("e"))
        {
            Save();
        }

        if (Input.GetKeyDown("m"))
        {
            StartCoroutine(Getwindowresult());
        }
    }

    private void Init()
    {
        _test.gameObject.SetActive(false);
        StartCallCamera();
    }

    /// <summary>
    ///  上傳服務(wù)器截圖
    /// </summary>
    /// <param name="action"></param>
    public void Save()
    {
        startPos = mCamera.WorldToScreenPoint(qr_transforms[0].position);
        endPos = mCamera.WorldToScreenPoint(qr_transforms[1].position);
        width = int.Parse(Mathf.Abs(startPos.x - endPos.x).ToString("F0"));
        height = int.Parse(Mathf.Abs(startPos.y - endPos.y).ToString("F0"));
        //計(jì)算鼠標(biāo)劃定范圍的長和寬~~
        //Debug.Log(w);
        //Debug.Log(h);
        StartCoroutine(GetCapture());
    }

    /// <summary>
    /// 開啟攝像頭
    /// </summary>
    private void StartCallCamera()
    {
        StartCoroutine("CallCamera");
    }

    /// <summary>
    /// 關(guān)閉攝像頭
    /// </summary>
    private void StopCallCamera()
    {
        if (webTex != null)
        {
            webTex.Stop();
        }
    }

    /// <summary>
    /// 重新拍照
    /// </summary>
    private void BackPhoto()
    {
        _test.gameObject.SetActive(false);
        StartCallCamera();
    }

    /// <summary>
    /// 拍照截圖
    /// </summary>
    private void CameraShor()
    {
        StopCallCamera();
        StartCoroutine("Shot");
    }

    /// <summary>
    /// 調(diào)用攝像頭
    /// </summary>
    /// <returns></returns>
    IEnumerator CallCamera()
    {
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if (Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            if (webTex != null)
                webTex.Stop();

            WebCamDevice[] devices = WebCamTexture.devices;
            string deviceName = devices[0].name;
            //設(shè)置攝像機(jī)攝像的區(qū)域    
            webTex = new WebCamTexture(deviceName, 1920, 1080, 60);

            cameraImage.texture = webTex;
            webTex.Play();//開始攝像    
        }
    }

    /// <summary>
    /// 拍照截圖
    /// </summary>
    /// <returns></returns>
    IEnumerator Shot()
    {
        if (Countdowns.Length != 0)
        {
            ///倒計(jì)時
            for (int i = 0; i < Countdowns.Length; i++)
            {
                countDownImage.sprite = Countdowns[i];
                yield return new WaitForSeconds(timing);
            }
        }

        ShotRect _shotRect = Capture.GetShotArea(_camera, transforms[0], transforms[1]);
        yield return new WaitForEndOfFrame();
        Texture2D texture = new Texture2D(_shotRect.w, _shotRect.h, TextureFormat.RGB24, false);
        texture.ReadPixels(new Rect(_shotRect.x, _shotRect.y, _shotRect.w, _shotRect.h), 0, 0, false);
        texture.Apply();

        _test.gameObject.SetActive(true);
        _test.texture = texture;

        StartCoroutine(DownLoadTexture(texture,"Start"));
    }

    /// <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();
    }

    /// <summary>
    /// 截圖上傳 
    /// </summary>
    /// <returns></returns>
    IEnumerator GetCapture()
    {
        //等待所有的攝像機(jī)跟GUI渲染完成
        yield return new WaitForEndOfFrame();
        Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false);
        //----------------------------------------------------------------------------計(jì)算區(qū)域----------------------------------------------------
        float vx = (startPos.x > endPos.x) ? endPos.x : startPos.x;                                 //取較小的x,y作為起始點(diǎn)
        float vy = (startPos.y > endPos.y) ? endPos.y : startPos.y;
        tex.ReadPixels(new Rect(vx, vy, width, height), 0, 0, true);
        //-----------------------------------------------------------------------------------------------------------------------------------------
        byte[] imagebytes = tex.EncodeToPNG();//轉(zhuǎn)化為png圖

        string timestamp = QR_Code.GetTimeStamp().ToString();

        //string filename = Application.streamingAssetsPath + "/" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + timestamp + ".png";
        //Debug.Log(string.Format("截屏了一張照片: {0}", filename));
        //File.WriteAllBytes(filename, imagebytes);

        QR_Code.instance.UpLoad(imagebytes, timestamp, qr_RawImage);
    }

    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(); //一定要清理游離資源。
    }

    //獲取像素
    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();
        //        texture.name = name ;
        byte[] pngData = GetJpgData(texture);
        return pngData;
    }

    //控制照片大小
    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;
    }

    /// <summary>
    /// 程序退出
    /// </summary>
    private void OnApplicationQuit()
    {
        StopCallCamera();
    }
}

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

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

  • 因?yàn)樘^于貪戀夢里的那些故事,所以我摁掉了無數(shù)的鬧鐘!慌亂中洗漱吹發(fā),看著鏡子里的自己,突然恍恍惚惚有點(diǎn)難過,倒不...
    瘋菇?jīng)鰈sabella閱讀 144評論 0 0
  • 《數(shù)字與數(shù)字的碰撞》 穿梭各地交定金, 晝夜不停搶付清。 低頭俯視吃一驚, 順豐貨物山堆成。 電話頻頻發(fā)貨中, 快...
    優(yōu)雅如楓閱讀 606評論 20 16
  • 最近重刷《舌尖上的中國》第一季,讓我對記憶中的農(nóng)村又懷念起來。 關(guān)于農(nóng)村生活的記憶,由于年紀(jì)太小而不太清晰,只零散...
    7個土豆閱讀 645評論 0 1
  • 【0511晨讀感想】 我的世界聽我的 有沒有過因?yàn)橐患ぷ鞯氖掠绊懙搅诵那?,然后?dǎo)致搞砸一堆事,最后覺得連生活都不...
    小二關(guān)閱讀 156評論 0 0

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