Unity3d – Capture images using device camera
This article will help you to understand the basics of unity3d image processing. After read this you will be able to,
- Access device camera and capture images.
- Save them into device.
- Load back saved images.
Where to Save ?
First things first, before capture images or access device camera, need to create a suitable folder for saving images. In unity we can get the persistent data path of target platform.
string path = Application.persistentDataPath + "/Documents/"; // Contains the path to a persistent data directory
This location won’t get delete with each update of the app. This is only suitable for saving data which are expected to be kept between runs. After, successfully retrieve the document path, let’s create folder inside it. Creating a sub folder will help to keep things nice and tidy :)
DirectoryInfo t = new DirectoryInfo(m_FileLocation); // Initializes a new instance of the DirectoryInfo class on the specified path. t.CreateSubdirectory("Unityimages"); // Creates a subdirectory or subdirectories on the specified path // The specified path can be relative to this instance of the DirectoryInfo class
Access device camera
By using WebCamTexture.devices, we can get a list of available cameras
WebCamDevice devices = WebCamTexture.devices;
For rendering live video input, need to create a new webcamTexture and passed the which device to be used as parameter. If we wont pass any device name or set a null string, the first device found will be used.
WebCamTexture m_WebCamTexture = new WebCamTexture(m_BackCam, 640, 480, 30); m_WebCamTexture.Play(); // Starts the camera
Capture image and Save
Using unity’s GetPixels method we can get an array of pixel colors of a texture. This array is flattened 2D array where pixels are played out row after row.
Color c; // Create color array c = m_WebCamTexture.GetPixels (); // Get an array of pixel colors of the 'm_WebCamTexture'
Now we have color array :) ,let’s create new texture 2d which has similar height and width to our webcam texture. Then apply previously grabbed color pixels into newly created texture 2d.
Texture2D snap = new Texture2D(m_WebCamTexture.width,m_WebCamTexture.height); snap.SetPixels(c); // Apply previously grabed color array into the 'snap' snap.Apply(); // Actually apply previous changers
Its time to save. make use of .net’s System.IO methods easily save created image into device.
System.IO.File.WriteAllBytes( m_FileLocation + "Unityimages/"+ fileName, snap.EncodeToPNG());
Load Saved Images
This is more like reverse of what we did in image save method. First read the contents in the file into byte array using File.ReadAllBytes. Then using this byte array, we can easily loads a jpg or PNG image.
Byte bytes = System.IO.File.ReadAllBytes(filePath); // Opens a binary file, reads the contents of the file into a byte array, and then closes the //file Texture2D tex = new Texture2D(640, 480); tex.LoadImage(bytes);