09 Sept 2014Unity15 Comments

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.

Application.persistentDataPath

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 :)

Access device camera

By using WebCamTexture.devices, we can get a list of available cameras

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.

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.

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.

Find more about SetPixels

Its time to save. make use of .net’s System.IO methods easily save created image into device.

File.WriteAllBytes

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.

Download complete unity project

Tags: