(1)启用摄像头
效果图:
代码如下:
/// <summary>
/// 摄像头
/// </summary>
public class UsingCamera : MonoBehaviour
{
public RawImage raw;
WebCamTexture camTexture;
void Start()
{
StartCoroutine(CallCamera());
}
//启用摄像头
IEnumerator CallCamera()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
try
{
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices; print(devices.Length);
if (devices.Length == 0)
{
Debug.Log($"WebError:\n未启用摄像头");
yield break;
}
string deviceName = devices[0].name;
print(deviceName);
camTexture = new WebCamTexture(deviceName, 800, 800, 12);
raw.texture = camTexture;
camTexture.Play();
}
}
catch
{
Debug.Log($"WebError:\n未启用摄像头");
}
}
}
(2)2021.6.2拍照
Texture2D t2dSave = null;
/// <summary>
/// 摄像头拍照
/// </summary>
public void Capture()
{
print("拍照");
t2dSave = null;
if (!camTexture || !camTexture.isPlaying) return;
t2dSave = new Texture2D(camTexture.width, camTexture.height);
t2dSave.SetPixels(camTexture.GetPixels());
t2dSave.Apply();
//camTexture.Stop();//Cannot get pixels when webcam is not running
camTexture.Pause();
}
Cannot get pixels when webcam is not running
保存图片的时候摄像头一定要属于运行状态哦!
/// <summary>
/// 保存
/// </summary>
public void Save(WebCamTexture t)
{
Texture2D t2d = new Texture2D(t.width, t.height, TextureFormat.ARGB32, false);
//将WebCamTexture 的像素保存到texture2D中
t2d.SetPixels(t.GetPixels());
t2d.Apply();
//编码
byte[] imageTytes = t2d.EncodeToJPG();
raws.texture = t2d;
//存储
File.WriteAllBytes(Application.streamingAssetsPath + "/头像/" + Time.time + ".jpg", imageTytes);
#if UNITY_EDITOR
UnityEditor.AssetDatabase.Refresh();//刷新Unity的资产目录
#endif
}