Dowload Code

Android SurfaceView Example

In android surfaceview example you will learn how to preview camera on surfaceview in android application using surface-view. How to apply color effects on camera preview.First of all i’ll give you explanation everything concerning classes of android surfaceview example tutorial.

These are the concerning things in this android surfaceview example tutorial.

  • Camera
  • Surface View
  • SurfaceHolder
  • Callback
  • FileOutputStream

Camera

Used to capture image and video.Some Android devices have front or some are not having that camera facility.Basic use of Cam.There are alot of Cam feature like you can detect face,apply color effects etc.So let’s talk about Effect.Here is the list of color effects method on camera hardware some might be supported on your device some might be not.

  • Camera.Parameters.EFFECT_AQUA
  • Parameters.EFFECT_NEGATIVE
  • Parameters.EFFECT_NONE
  • Parameters.EFFECT_MONO
  • Parameters.EFFECT_BLACKBOARD
  • Parameters.EFFECT_SEPIA
  • Parameters.EFFECT_WHITEBOARD
  • Parameters.EFFECT_POSTERIZE
  • Parameters.EFFECT_SOLARIZE

SurfaceView

Surface View class provides dedicated surface within view hierarchy.Surface View is basically extends from View class.Surface View can be used to place overlays buttons or any other like camera preview.

Surface Holder

Surface Holder interface is used to hold display surface.Surface Holder can be used to edit pixels,format or changes to surface.Access to surface is basically retrieved using getholder() method.

Callback

Callback is kind of confusing term or you can say interface method.Basically Callback is a piece of executable code means an object which will passed to any function as argument.For example let’s you have two buckets.If you hit first then something happen and if you hit second nothing happen.It means when first event occur(hit) it’s function will be called.

Second Description might clear good enough.
You use an interface of which receiver object will call one or more methods connected to that object.

FileOutputStream

This class is used to write stream of bytes to a file.If that file already exist it’ll overwrite otherwise create new file.For more detail.

Ok you are done with classes information which you will use in this android surfaceview example tutorial.

So now go ahead and create new android surfaceview example application project.

surfaceview,Android Surfaceview,android surfaceview example,surfaceview example,

Now go to your xml layout put surfaceView xml code or drag and drop it from (Advance)  UI Pallate.Also put button to capture an image.Your xml code will look like this.

surfaceview,Android Surfaceview,android surfaceview example,surfaceview example,

Now you add permission for camera hardware like this.

surfaceview,Android Surfaceview,android surfaceview example,surfaceview example,
Now go to MainActivity.java class make sure your activity at start should contain this code.Nothing else.

public class MainActivity extends Activity{
        @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
        }
}

Next you will create Button  variable.Refer it’s id and apply click event on that.After that your MainActivity.java class will look like this.

public class MainActivity extends Activity{
        Button cap;    // image capturing button
        @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
                // refering button id
		cap = (Button) findViewById(R.id.takepicture);
		// click event on button
		cap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        }
}

Now next step is to implement an interface SurfaceHolder.Callback in your MainActivity.java class.Then add unimplemented methods of Surface.Then you MainActivity.java class will be like this.

public class MainActivity extends Activity implements SurfaceHolder.Callback{
        Button cap;    // image capturing button
        @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
                // refering button id
		cap = (Button) findViewById(R.id.takepicture);
		// click event on button
		cap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        }
        @Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
              // TODO Auto-generated method stub
        }
        @Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
        } 
        @Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
        }
}

Now next declare variables for Camera,SurfaceView,SurfaceHolder and Camera condition like this.

public class MainActivity extends Activity implements SurfaceHolder.Callback{
        Camera camera; // camera_class variable
	SurfaceView camView; // drawing preview using this variable
	SurfaceHolder surfaceHolder; // variable to hold surface for surfaceView which means display
	boolean camCondition = false;  // conditional variable for preview checking and set to false
        Button cap;    // image capturing button
        @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
                // refering button id
		cap = (Button) findViewById(R.id.takepicture);
		// click event on button
		cap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        }
        @Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
              // TODO Auto-generated method stub
        }
        @Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
        } 
        @Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
        }
}

Next you will use getWindow() method to get preview window  and set it pixel format to UNKNOWN.Then refer the surfaceView which you have used in XML and provide access to the surfaceHolder using getholder() method.Then add callback method to that particular context means MainActivity.java class.Next set surface type to NORMAL like this.

public class MainActivity extends Activity implements SurfaceHolder.Callback{
        Camera camera; // camera_class variable
	SurfaceView camView; // drawing preview using this variable
	SurfaceHolder surfaceHolder; // variable to hold surface for surfaceView which means display
	boolean camCondition = false;  // conditional variable for  preview checking and set to false
        Button cap;    // image capturing button
        @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
                // getWindow() to get window and set it's pixel format which is UNKNOWN
		getWindow().setFormat(PixelFormat.UNKNOWN);
		// refering the id of surfaceView
		camView = (SurfaceView) findViewById(R.id.camerapreview);
		// getting access to the surface of surfaceView and return it to surfaceHolder
		surfaceHolder = camView.getHolder();
		// adding call back to this context means MainActivity
		surfaceHolder.addCallback(this);
		// to set surface type
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
		
                // refering button id
		cap = (Button) findViewById(R.id.takepicture);
		// click event on button
		cap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        }
        @Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
              // TODO Auto-generated method stub
        }
        @Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
        } 
        @Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
        }
}

Now When First surface created your camera will be at display on surfaceView using open() method.Set it’s orientation to 90 degree means vertical within the surfaceCreated() method.When you leave the application or stop the application you will stop camera within surfaceDestroyed() method.

public class MainActivity extends Activity implements SurfaceHolder.Callback{
        Camera camera; // camera_class variable
	SurfaceView camView; // drawing  preview using this variable
	SurfaceHolder surfaceHolder; // variable to hold surface for surfaceView which means display
	boolean camCondition = false;  // conditional variable for  preview checking and set to false
        Button cap;    // image capturing button
        @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
                // getWindow() to get window and set it's pixel format which is UNKNOWN
		getWindow().setFormat(PixelFormat.UNKNOWN);
		// refering the id of surfaceView
		camView = (SurfaceView) findViewById(R.id.camerapreview);
		// getting access to the surface of surfaceView and return it to surfaceHolder
		surfaceHolder = camView.getHolder();
		// adding call back to this context means MainActivity
		surfaceHolder.addCallback(this);
		// to set surface type
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
		
                // refering button id
		cap = (Button) findViewById(R.id.takepicture);
		// click event on button
		cap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        }
        @Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
              // TODO Auto-generated method stub
        }
       @Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		camera = Camera.open();
		camera.setDisplayOrientation(90);
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		camera.stopPreview();
		camera.release();
		camera = null;
		camCondition = false;
	}

}

Next is surfaceChanged() method.Within this method we put code to set camera parameters like color effect and preview to surfaceHolder.Set camera condition to true which camera is there in your device like this.

public class MainActivity extends Activity implements SurfaceHolder.Callback{
        Camera camera; // camera_class variable
	SurfaceView camView; // drawing preview using this variable
	SurfaceHolder surfaceHolder; // variable to hold surface for surfaceView which means display
	boolean camCondition = false;  // conditional variable for preview checking and set to false
        Button cap;    // image capturing button
        @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
                // getWindow() to get window and set it's pixel format which is UNKNOWN
		getWindow().setFormat(PixelFormat.UNKNOWN);
		// refering the id of surfaceView
		camView = (SurfaceView) findViewById(R.id.camerapreview);
		// getting access to the surface of surfaceView and return it to surfaceHolder
		surfaceHolder = camView.getHolder();
		// adding call back to this context means MainActivity
		surfaceHolder.addCallback(this);
		// to set surface type
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
		
                // refering button id
		cap = (Button) findViewById(R.id.takepicture);
		// click event on button
		cap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
        }
        


}

Till here if you run your android application project.Your camera preview will display on surfaceView.
Next you will write function for image capturing button.In that function you will use PictureCallback interface to supply image data.And Store in a directory called “AndroidCodec_”.Next you will call takepicture method on button click passing just one parameter mPictureCallBack others should be null.So with this your final Main Activity java class looks.
MainActivity.java

package androidcodec.camerapreview;
/*
 * 
 * All Rights Reserved By: Farhan Rasheed
 * 
 * */

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;


public class MainActivity extends Activity implements SurfaceHolder.Callback {

	@SuppressWarnings("deprecation")
	Camera camera; // camera_class variable
	SurfaceView camView; // drawing  preview using this variable
	SurfaceHolder surfaceHolder; // variable to hold surface for surfaceView which means display
	boolean camCondition = false;  // conditional variable for  preview checking and set to false
	Button cap;    // image capturing button
	
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// getWindow() to get window and set it's pixel format which is UNKNOWN
		getWindow().setFormat(PixelFormat.UNKNOWN);
		// refering the id of surfaceView
		camView = (SurfaceView) findViewById(R.id.camerapreview);
		// getting access to the surface of surfaceView and return it to surfaceHolder
		surfaceHolder = camView.getHolder();
		// adding call back to this context means MainActivity
		surfaceHolder.addCallback(this);
		// to set surface type
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
		
		
		// refering button id
		cap = (Button) findViewById(R.id.takepicture);
		// click event on button
		cap.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// calling a method of cameraa class takepicture by passing one picture callback interface parameter
				camera.takePicture(null, null, null, mPictureCallback);
			}
		});
	}
	 // picture taken image and store in directory
	@SuppressWarnings("deprecation")
	Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
	        public void onPictureTaken(byte[] data, Camera c) {
	         
	         FileOutputStream outStream = null;
	          try {
	          
	          // Directory and name of the photo. We put system time
	          // as a postfix, so all photos will have a unique file name.
	          outStream = new FileOutputStream("/sdcard/AndroidCodec_" +
	              System.currentTimeMillis()+".jpg");
	          outStream.write(data);
	          outStream.close();
	         } catch (FileNotFoundException e) {
	          e.printStackTrace();
	         } catch (IOException e) {
	          e.printStackTrace();
	         } finally {
	        }
	           
	        }
	    };
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		// stopping
		if(camCondition){
			camera.stopPreview(); // stop preview using stopPreview() method
			camCondition = false; // setting  condition to false means stop
		}
		// condition to check whether your device havecamera or not
		if (camera != null){
			try {
				Camera.Parameters parameters = camera.getParameters();
				parameters.setColorEffect(Camera.Parameters.EFFECT_SEPIA); //applying effect on camera
				camera.setParameters(parameters); // setting  parameters
				camera.setPreviewDisplay(surfaceHolder); // setting preview of camera
				camera.startPreview();  // starting  preview			
				camCondition = true; // setting  to true which means having camera
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		camera = Camera.open();   // opening 
		camera.setDisplayOrientation(90);   // setting  preview orientation
	}
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		camera.stopPreview();  // stopping  preview
		camera.release();       // releasing 
		camera = null;          // setting  to null when left
		camCondition = false;   // setting  condition to false also when exit from application
	}
}

Run your android surfaceview example application project.

I have added every line comment for you convenience.Final Preview of your android surfaceview example app with color effect.

surfaceview,Android Surfaceview,android surfaceview example,surfaceview example,

I hope this android surfaceview example tutorial is helpful for you.

Don’t forget to leave your feedback.

Thanks.