Android Studio Camera Tutorial
Android Studio provides built-in support for working with the Camera. In this tutorial, we will learn how to use the Android Studio Camera API to develop a basic Camera application.
Syntax
The syntax for using the Camera in Android Studio is as follows:
// Initialize the Camera
Camera camera = Camera.open();
// Set the Camera Parameters
Camera.Parameters parameters = camera.getParameters();
// Set the Preview Size
parameters.setPreviewSize(width, height);
// Set the Picture Size
parameters.setPictureSize(width, height);
// Set the Focus Mode
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// Apply the Parameters
camera.setParameters(parameters);
// Start the Preview
camera.startPreview();
Example
Let's create a basic Camera application that allows the user to preview and capture images:
public class MainActivity extends AppCompatActivity {
private CameraPreview mCameraPreview;
private Camera mCamera;
private Button mButtonCapture;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new instance of CameraPreview
mCameraPreview = new CameraPreview(this);
// Add the CameraPreview to the layout
FrameLayout previewLayout = findViewById(R.id.camera_preview);
previewLayout.addView(mCameraPreview);
// Create a new instance of Camera
mCamera = getCameraInstance();
// Set the Camera Preview Display
mCameraPreview.setCamera(mCamera);
// Capture Button
mButtonCapture = findViewById(R.id.button_capture);
mButtonCapture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/** Camera Picture Callback */
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// Save the Image to Storage
Uri imageUri = saveImage(data);
// Display a Toast to Show Image URI
Toast.makeText(getApplicationContext(), "Image Saved: " + imageUri.toString(), Toast.LENGTH_SHORT).show();
// Restart the Camera Preview
mCamera.startPreview();
}
};
/** Save Image to Storage */
private Uri saveImage(byte[] data){
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();
}
String fileName = "image_" + System.currentTimeMillis() + ".jpg";
File output = new File(imagesFolder, fileName);
try {
FileOutputStream fos = new FileOutputStream(output);
fos.write(data);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return Uri.fromFile(output);
}
@Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
@Override
protected void onResume() {
super.onResume();
if (mCamera == null) {
mCamera = getCameraInstance(); // acquire the camera on resume
mCameraPreview.setCamera(mCamera); // set the camera to the preview on resume
}
}
/** Release the Camera */
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
}
Output
The output of the above code will be a simple Camera application that allows the user to preview and capture images.
Explanation
We first create a new instance of the CameraPreview class, which is a subclass of SurfaceView that handles displaying the camera preview. We then add this view to our layout.
We then create a new instance of the Camera class, and set it as the camera for our preview using the setCamera() method of the CameraPreview class.
We add an OnClickListener to the capture button, which calls the takePicture() method of the Camera class to capture an image. We then save the image to the device's storage, and display a Toast message showing the URI of the saved image.
We also include methods for releasing the camera when the application is paused, and re-acquiring it when the application is resumed.
Use
The Android Studio Camera API can be used to develop various camera applications, including photo and video capture, barcode scanning, and more.
Important Points
- The Camera API requires the Camera permission in the AndroidManifest.xml file.
- The Camera must be safely released when not in use.
- The Camera Preview must be started before capturing an image.
- The Camera Preview must be released when the application is paused.
Summary
In this tutorial, we learned how to use the Camera API in Android Studio to develop a basic Camera application. We also learned about important considerations such as Camera permission, safe Camera release, starting and stopping the Camera Preview, and more.