using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class TakePhotoCamera : MonoBehaviour
{
public static TakePhotoCamera instance;
public byte[] imageTytes;
//摄像头图像类,继承自texture
public WebCamTexture tex;
/// <summary>
/// 图片保存路径
/// </summary>
public string picPath = "";
private void Awake()
{
instance = this;
}
// Start is called before the first frame update
void Start()
{
StartCoroutine(OpenCamera());
}
IEnumerator OpenCamera()
{
//等待用户允许访问
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
//如果用户允许访问,开始获取图像
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
//先获取设备
WebCamDevice[] device = WebCamTexture.devices;
string deviceName = device[0].name;
//然后获取图像
tex = new WebCamTexture(deviceName);
//将获取的图像赋值
// ma.material.mainTexture = tex;
//开始实施获取
tex.Play();
}
}
public void TakingPhoto(string pictureType)
{
Save(tex,pictureType);
}
public void Save(WebCamTexture t,string pictureType)
{
Texture2D t2d = new Texture2D(t.width, t.height, TextureFormat.ARGB32, true);
//将WebCamTexture 的像素保存到texture2D中
t2d.SetPixels(t.GetPixels());
t2d.Apply();
imageTytes = t2d.EncodeToJPG();
picPath = Application.persistentDataPath + "/" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".jpg";
File.WriteAllBytes(picPath, imageTytes);
}
void StopCamera()
{
//等待用户允许访问
//Application.RequestUserAuthorization(UserAuthorization.WebCam);
//如果用户允许访问,开始获取图像
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
//先获取设备
WebCamDevice[] device = WebCamTexture.devices;
string deviceName = device[0].name;
tex.Stop();
}
}
private void OnDisable()
{
StopCamera();
}
}
标签:tex,拍照,string,void,相机,WebCamTexture,unity,using,public From: https://www.cnblogs.com/guangzhiruijie/p/16968712.html