Unity3d : WebCamTexture Convert To Texture2D

General case, we can use these scripts below to  display camera on the scene in the Unity3d.

  WebCamTexture wc = new WebCamTexture ();
  GameObject.Find (“/plane”).renderer.material.mainTexture = wc;
  wc.Play ();

But sometimes we want to save camera to image, or realized video streaming. We can use WebcamTexture.GetPixels() and Texture2D.SetPixels(), but you must noticed returning width and height.

WebcamTexture construct can give requested width and height parameters. The issue occur when the parameters does not be supported by the chosen camera.

  WebCamTexture wc = new WebCamTexture (160, 120);
  wc.play();
  Texture2D t = new Texture2D(wc.width, wc.height);
  t.SetPixels(wc.GetPixels());
  t.Apply();

On the Android, above scripts can worked fine, but on the iPhone 5S that texture t just showing blur. The reason is even iphone camera doesn’t suport requested width and height, the property width and height of WebCamTexture still returning requested values instead real values of camera.

So the simplest solution is using WebCamTexture() to replace WebCamTexture(160, 120). At last, I made an easy sample here. Please feel free to download and comment anything.

WebCamTextureToTexture2D.zip

Reference :
Unity – Scripting API: WebCamTexture
http://docs.unity3d.com/ScriptReference/WebCamTexture.html

1 關於 “Unity3d : WebCamTexture Convert To Texture2D” 的評論

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

數學難題 * 限制時效已用盡。請重新載入驗證碼。