目录
1、功能说明
使用unity调用外置摄像头完成拍照并保存图片功能,同时支持视频播放和视频切换。
2、效果展示
最终效果图如下所示:
其中右下角为视频播放区域,可以随意切换自己准备好的视频文件。注意在下图红线所示区域添加视频文件。
3、实现代码
完整代码如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime .Serialization.Formatters.Binary;
using System.Threading;
public class takePhoto : MonoBehaviour
{
public string deviceName;
//接收返回的图片数据
WebCamTexture tex;
public int a=0, b=0, c=Screen.width, d=Screen.height, e=0, f=0;//测试用变量,改变值并测试
void OnGUI()
{
if(tex!=null)
{
// 捕获截图大小 —距X左屏距离 | 距Y上屏距离
GUI.DrawTexture(new Rect(Screen.width/2-150,Screen.height/2-190,560,400),tex);
}
}
public void startCamera(){
StartCoroutine(start());
}
public void mtakePhoto(){
StartCoroutine(getTexture());
}
public void pauseCamera(){
StartCoroutine(start());
}
public void stopCamera(){
tex.Stop ();
StopAllCoroutines();
}
/// <summary>
/// 捕获窗口位置
/// </summary>
public IEnumerator start()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
if(devices !=null){
deviceName= devices[0].name;
tex=new WebCamTexture(deviceName,c,d,12);
tex.Play();
}
}
}
/// <summary>
/// 获取截图
/// </summary>
/// <returns>The texture.</returns>
public IEnumerator getTexture()
{
yield return new WaitForEndOfFrame();
byte[] byt = GetPhotoPixel(tex);
File.WriteAllBytes(Application.dataPath+"/Photoes/"+Time.time+".jpg",byt);
tex.Play();
}
//获取像素
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 quality = 75 ;
while(quality > 20)
{
data = te.EncodeToJPG(quality);
int size = data.Length/1024;
if( size > 30 )
{
quality -=5;
}
else
{
break ;
}
}
return data ;
}
}