您的位置:首页 > 移动开发 > Unity3D

[置顶] Unity摄像头截图功能演示

2018-03-19 18:11 393 查看



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

public class WebCamera : MonoBehaviour {
[Tooltip("返回的照片数据,根据返回的照片,进行照片的识别和比对认证等等!"), Space(5)]
[Header("摄像头拍摄的照片"),]
public WebCamTexture camTexture;//摄像头拍下的图片数据

[Header("摄像头设备名")]
private WebCamDevice[] devices;

[Tooltip("USB摄像头设备"), Space(5)]
[Header("摄像头设备名")]
public string deviceName;//摄像头设备名称
public static Texture2D tex2D;

public bool isClick;//是否点击了按钮

public static float ScreenShotTexture2D = 0f;//截取到图片编号(名称)
public Text DebugScreenShotText;//用于输出打印截图的名称(为了效验)

//初始化摄像头显示的图像的大小
private void Start()
{
isClick = false;
camTexture = new WebCamTexture(deviceName, 800, 600, 60);
}
//通过GUI绘制摄像头要显示的窗口
private void OnGUI()
{
//首先根据摄像头展示的画面来判断摄像头是否存在
if(isClick == true&&camTexture != null)
{
//绘制画面(Screen.width / 2 - 150f, Screen.height / 2 - 290,这里是画面距离场景的高和宽的限制)
//800, 600是和camTexture的画面一样大的绘制窗口
GUI.DrawTexture(new Rect(Screen.width / 2 - 150f, Screen.height / 2 - 290, 800, 600), camTexture);
}
if(isClick == false && camTexture != null)//不显示画面(没写这个步骤之前有个坑)
{
GUI.DrawTexture(new Rect(Screen.width / 2 - 150f, Screen.height / 2 - 290, 0, 0), camTexture);
}
}

//打开摄像机的方法
public void OpenWebCamDevice()
{
isClick = true;
if(isClick == true)
{
//用户授权打开摄像头
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
devices = WebCamTexture.devices;//显示画面的设备就是要打开的摄像头
deviceName = devices[0].name;//获取到设备名称
camTexture.Play();//开启摄像头
}
}
}
//关闭摄像头
public void CloseWebCamDevice()
{
if(isClick== true && camTexture != null)
{
isClick = false;

}
}
//截图按钮事件
public void OnClickBtnScreenShotTex2D()
{
OpenWebCamDevice();//先打开摄像头

Invoke("StartScreenShot", 3f);//几秒后截图
}
void StartScreenShot()
{
camTexture.Pause();//截图暂停一下
StartCoroutine("ScreenShot");//启动协程截图
}

IEnumerator ScreenShot()
{
yield return new WaitForEndOfFrame();//等某一帧结束
tex2D = new Texture2D(800, 600, TextureFormat.RGB24, true);//截图的大小
tex2D.ReadPixels(new Rect(Screen.width / 2 - 150, Screen.height / 2 - 290, 800, 600), 0, 0, false);//截取的区域
tex2D.Apply();
byte[] by = tex2D.EncodeToJPG();//将截取到的图片转换成字节数据
camTexture.Play();//摄像头继续开启
ScreenShotTexture2D = Time.time;
File.WriteAllBytes(Application.dataPath + "/ScreenShot/" + ScreenShotTexture2D + ".jpg", by);
DebugScreenShotText.text = ScreenShotTexture2D.ToString();
Debug.Log("当前截取到图片名称为:" + ScreenShotTexture2D);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: