Hey everybody!!!
I want to take a picture from my web camera but the programm decides that my camera is not running.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class Open_Camera : MonoBehaviour {
public RawImage rawimage;
private WebCamTexture webCam = null;
void Start()
{
WebCamTexture webCam = new WebCamTexture();
rawimage.texture = webCam;
rawimage.material.mainTexture = webCam;
webCam.Play();
// I tried to use the function code inside Start() to test it, but all I get is a black picture.
//I think black picture is because it takes the picture before camera open.
/*Texture2D photo = new Texture2D(rawimage.texture.width, rawimage.texture.height);
photo.SetPixels(webCam.GetPixels());
photo.Apply();
byte[] bytes = photo.EncodeToPNG();
File.WriteAllBytes("Assets/Samples/New Pics/" + "testing.png", bytes);
counter++;
*/
}
private void Update()
{
WebCamTexture webCam = new WebCamTexture();
if (Input.GetMouseButtonDown(0))
{
saveImage(webCam);
webCam.Stop();
}
}
string path = "A_path"; //this is not the path I use.
int counter = 0;
void saveImage(WebCamTexture x)
{
Texture2D photo = new Texture2D(rawimage.texture.width, rawimage.texture.height, TextureFormat.ARGB32, false);
photo.SetPixels(x.GetPixels());
Debug.Log("test");
photo.Apply();
byte[] bytes = photo.EncodeToPNG();
File.WriteAllBytes("Assets/Samples/New Pics/" + (counter.ToString() + "testing.png"), bytes);
counter++;
}
}
Also when i run it I get Cannot get pixels when webcam is not running. Like something is closing my camera. Thnx for the help