using UnityEngine;
using System.Collections;
using System.IO;
public class CameraController : MonoBehaviour {
public stringdeviceName;
public WebCamTexturewebTex;
public GameObjectobjCameraController;
public GameObjectobjAvatar;
public GameObjectImgAtlas;
public stringstrTempTime="";
// Use this forinitialization
void Start () {
}
// Update is called once perframe
void Update () {
if(strTempTime!="")
{
// GameObject.Find("pig5").GetComponent().mainTexture= Resources.Load(strTempTime.ToString(), typeof(Texture)) asTexture;
// print("44444:"+strTempTime);
}
}
///
/// 调用摄像机
///
///
IEnumeratorCallTheCamera()
{
yield returnApplication.RequestUserAuthorization(UserAuthorization.WebCam);
if(Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices =WebCamTexture.devices;
deviceName =devices[0].name;
//摄像机摄像的区域
webTex = newWebCamTexture(deviceName, 400, 300, -112);
GameObject.Find("CameraTexture").GetComponent().mainTexture= webTex;
webTex.Play();
}
}
///
/// 获取并保存texture
///
///
IEnumeratorGetTexture2D()
{
print(GameObject.Find("CameraTexture").transform.localPosition);
yield returnnew WaitForEndOfFrame();
Texture2D t =newTexture2D(GameObject.Find("CameraTexture").GetComponent().mainTexture.width,GameObject.Find("CameraTexture").GetComponent().mainTexture.height);
t.ReadPixels(newRect(15, 177, 406.5f, 281.6f), 0, 0, false);
t.Apply();
//把图片数据转换为byte数组
byte[] byt =t.EncodeToPNG();
//然后保存为图片
strTempTime= Time.time.ToString();
print("11111:"+strTempTime);
File.WriteAllBytes(Application.dataPath +"/Resources/" + strTempTime + ".jpg", byt);
print("22222"+strTempTime);
//GameObjectatlasPrefab = Resources.Load("TempAtlas") as GameObject;
// Instantiate(ImgAtlas) as GameObject;
// tempA.GetComponent().spriteList.Add(
//
UnityEditor.AssetDatabase.Refresh();
//yieldreturn new WaitForSeconds(1);
GameObject.Find("pig5").GetComponent().mainTexture= Resources.Load(strTempTime.ToString(), typeof(Texture)) asTexture;
print("33333"+strTempTime);
// NGUITools.AddSprite(tempA,tempA.GetComponent(), "tempSprite");
// UIAtlas atlas = (Instantiate(ImgAtlas) asGameObject).GetComponent();
// Texture text =Resources.Load(Application.dataPath + "/Resources/" + strTempTime +".jpg", typeof(Texture)) as Texture;
// print(atlas.ToString());
//UISlicedSpritessprite = NGUITools.AddWidget(Game);
//GameObject.Find("pig5").GetComponent().s
//UIAtlasatlas = Resources.Load(Application.dataPath + "/test/" + "CameraAtlas", typeof(UIAtlas)) as UIAtlas;
//print(atlas.ToString());
// objAvatar.GetComponent().spriteName= atlas.name;//this.gameObject.GetComponent().spriteName;
//objCameraController.SetActive(false);
}
void CameraStart()
{
StartCoroutine("CallTheCamera");
}
void CameraSStart()
{
StartCoroutine("GetTexture2D");
}
void CameraRestart()
{
webTex.Play();
}
void CameraPause()
{
webTex.Pause();
}
voidClickCameraBtn()
{
objCameraController.SetActive(true);
}
}
原文地址:http://blog.sina.com.cn/s/blog_697b1b8c0101dqb3.html