本类的功能是调用一台电脑上的多个摄像头,显示在UI上,并可以保存到本地
1.打开摄像头,并将摄像机里的内容显示到图片上
public IEnumerator TurnOnAllCamera(RawImage[] rayImages)
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);//授权
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
Debug.Log("有 " + devices.Length + " 个摄像机");
for (int i = 0; i < devices.Length; i++)
{
if (devices != null)
{
deviceName[i] = devices[i].name;
//设置摄像机摄像的区域
tex[i] = new WebCamTexture(deviceName[i], 400, 400, 30);
tex[i].Play();//开始摄像
rayImages[i].texture = tex[i];
textures[i] = tex[i];
Debug.Log("宽:" + rayImages[i].texture.width + " 高: " + rayImages[i].texture.height);
}
}
}
}
rawImages为显示摄像机内容的组件,调用时赋值即可
2.拍照并保存
public void StartPhotograph(int id,string iconName)
{
tex[id-1].Pause();
SaveTextureToFile(TextureToTexture2D(textures[id-1]), iconName+id.ToString() + ".png");
}
功能实现:保存Texture
/// <summary>
/// 保存Texture
/// </summary>
/// <param name="texture2D">要保存的图片</param>
/// <param name="fileName">保存的图片的名称</param>
void SaveTextureToFile(Texture2D texture2D, string fileName)
{
var bytes = texture2D.EncodeToPNG();
//Application.dataPath
//Application.persistentDataPath
JudgementOrCreate("/Icons");
var file = File.Open(Application.persistentDataPath +"/Icons"+ "/" + fileName, FileMode.Create);
//Debug.Log(Application.dataPath + "/" + fileName);
var binary = new BinaryWriter(file);
binary.Write(bytes);
file.Close();
}
创建保存图片的文件夹
/// <summary>
/// 判断是否有存储头像文件夹,如果没有,创建一个空文档。本机地址,相对路径。
/// </summary>
void JudgementOrCreate(string path)
{
if (!Directory.Exists(Application.persistentDataPath + path))
{
Debug.Log(Application.persistentDataPath);
Directory.CreateDirectory(Application.persistentDataPath + path);
print("文件夹不存在,创建");
}
}
将Texture转成Texture2D
private Texture2D TextureToTexture2D(Texture texture)
{
//Texture2D texture2D = new Texture2D(texture.width, texture.height, TextureFormat.RGBA32, false);
Texture2D texture2D = new Texture2D(300, 300, TextureFormat.RGBA32, false);
RenderTexture currentRT = RenderTexture.active;
//RenderTexture renderTexture = RenderTexture.GetTemporary(texture.width, texture.height, 32);
RenderTexture renderTexture = RenderTexture.GetTemporary(300, 300, 32);
Graphics.Blit(texture, renderTexture);
RenderTexture.active = renderTexture;
//texture2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
texture2D.ReadPixels(new Rect(0, 0, 300, 300), 0, 0);
texture2D.Apply();
RenderTexture.active = currentRT;
RenderTexture.ReleaseTemporary(renderTexture);
return texture2D;
}
以上就是完整的调用摄像机拍照保存的全部代码
摄像机不用的时候记得关闭哦
//关闭摄像机
public void StopCamera()
{
for(int i = 0; i < tex.Length; i++)
{
tex[i].Stop();
}
}