unity调用摄像头拍照

 我的unity调用摄像头拍照

因为做的是pc端的,所以不知道手机上效果是怎样的,据说代码是完全相同的微笑

废话不说,上代码,

打开摄像头代码:

/// <summary>
		/// Opens the camera
		/// </summary>
		/// <returns>The camera.</returns>
		IEnumerator OpenCamera()
		{
			yield return Application.RequestUserAuthorization (UserAuthorization.WebCam);
			if (Application.HasUserAuthorization (UserAuthorization.WebCam)) {
				WebCamDevice[] devices = WebCamTexture.devices;
				webCam = new WebCamTexture (devices [0].name, Screen.width, Screen.height, 12);
				image_userIcon.texture = webCam;
				webCam.Play ();
			}
		}
保存图片代码如下:

/// <summary>
		/// Gets the texture2d.
		/// </summary>
		/// <returns>The texture2d.</returns>
		IEnumerator GetTexture2d()
		{
			yield return new WaitForEndOfFrame();
			RectTransform rt = image_userIcon.GetComponent<RectTransform> ();
			Vector2 v2Min = new Vector2( rt.anchorMin.x * Screen.width,rt.anchorMin.y * Screen.height);
			Vector2 v2Max = new Vector2( rt.anchorMax.x * Screen.width,rt.anchorMax.y * Screen.height);
			Texture2D t = new Texture2D((int)(v2Max.x-v2Min.x),(int)(v2Max.y-v2Min.y));//要保存图片的大小
			//截取的区域
			t.ReadPixels(new Rect (v2Min.x,v2Min.y,(int)(v2Max.x-v2Min.x),(int)(v2Max.y-v2Min.y)),0,0,false);
			t.Apply();
			image_userIcon.texture = t;
			//把图片数据转换为byte数组

			byte[] byt = t.EncodeToPNG();

			//然后保存为图片

			File.WriteAllBytes(Application.dataPath + "/StreamingAssets/shexiang/" + Time.time + ".jpg", byt);
			webCam.Pause ();
		}
运行完这段效果大概是这样滴:


猜你喜欢

转载自blog.csdn.net/write_the_code/article/details/73275396
今日推荐