Android Camera Source Code: A Complete Guide to Implementing Camera Features
The Android camera is one of the most widely used features in mobile devices, enabling users to capture photos, record videos, and use various imaging capabilities within apps. Whether you're developing an app that requires basic photo capturing or more advanced features like image processing and live video streaming, understanding how to use the Android camera is essential.
This guide will provide you with a complete Android Camera source code to help you integrate camera functionalities into your own app. We will walk through the process of setting up camera access, handling camera permissions, capturing photos, recording videos, and more.
Key Concepts for Android Camera Integration
Before diving into the code, let's go over some key concepts that are important when working with the Android camera:
-
Permissions:
- Android requires the appropriate permissions to access the device’s camera. These permissions must be declared in the app's
AndroidManifest.xmlfile.
- Android requires the appropriate permissions to access the device’s camera. These permissions must be declared in the app's
-
Camera API:
- Camera1 API: The original camera API, which provides direct control over the camera hardware. It is now deprecated, and new apps should use the Camera2 API.
- Camera2 API: A more modern and flexible API that provides enhanced camera control, including manual focus, exposure, and white balance adjustments.
-
SurfaceView or TextureView:
- To display the camera preview, you need to use a
SurfaceVieworTextureView, which acts as the container for the preview output from the camera.
- To display the camera preview, you need to use a
-
Camera Intent:
- Android provides an intent-based mechanism for launching the camera app and capturing photos. This is useful for simpler camera integration where you don’t need to manage the camera hardware directly.
Setting Up Permissions
To use the camera on Android, you need to request camera permissions. In your AndroidManifest.xml, add the following lines to declare permissions:
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
These permissions are necessary to access the camera and save captured images to the device's storage.
Implementing Camera Features with Camera2 API
Below is the source code for setting up a basic camera functionality using the Camera2 API. This includes setting up the camera preview and taking a photo.
Step 1: Setting Up the Camera2 API
The Camera2 API is more advanced than the old Camera API and provides finer control over the camera, such as capturing images with specific settings (e.g., exposure, focus, and ISO).
- Initialize Camera Manager
In the Activity or Fragment where you want to implement the camera, you first need to get a reference to the Camera Manager.
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
- Request Camera Permission at Runtime
Since Android 6.0 (API level 23), you need to request permissions at runtime for accessing the camera.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
CAMERA_PERMISSION_REQUEST_CODE);
}
- Open the Camera
Once the permissions are granted, you can open the camera.
private void openCamera() {
try {
String cameraId = cameraManager.getCameraIdList()[0]; // Select the first camera (usually rear-facing)
CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
// Camera opened successfully
cameraDevice = camera;
createCameraPreviewSession();
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
camera.close();
}
@Override
public void onError(@NonNull CameraDevice camera, int error) {
camera.close();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
- Set Up Camera Preview
To display the camera preview, you need to set up a SurfaceView or TextureView to show the camera feed. The preview will be rendered to a Surface, which is linked to the view.
private void createCameraPreviewSession() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
Surface surface = new Surface(texture);
CaptureRequest.Builder captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
if (cameraDevice == null) {
return;
}
captureSession = session;
try {
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
captureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
// Handle configuration failure
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
Step 2: Capturing Photos
To capture an image, you need to issue a capture request and specify the image format. You can save the captured image to a file or handle it in-memory.
private void takePicture() {
try {
CameraCaptureSession captureSession = this.captureSession;
if (captureSession == null) {
return;
}
CaptureRequest.Builder captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureRequestBuilder.addTarget(imageReader.getSurface());
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
captureSession.stopRepeating();
captureSession.capture(captureRequestBuilder.build(), new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
// Photo capture completed, handle the captured image here
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
In this code, imageReader is an instance of ImageReader used to obtain the image after it has been captured.
Step 3: Handling Camera Output and Saving the Image
Once the photo has been captured, you can save it to the device storage using the ImageReader and FileOutputStream.
private void saveImageToStorage(Image image) {
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(new File(getExternalFilesDir(null), "captured_image.jpg"));
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
image.close();
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Conclusion
Integrating the Android camera into your app using the Camera2 API allows you to leverage modern features such as high-resolution image capture, live previews, and manual control over camera settings. While the Camera2 API is more complex, it offers complete flexibility and control for advanced use cases.
By following the source code provided in this guide, you can quickly set up camera functionalities such as capturing images, displaying live previews, and saving photos to the device storage.
For simpler applications, you may choose to use the Camera Intent or Camera1 API, but for high-end, professional apps, the Camera2 API will provide the best performance and flexibility. Always ensure that your app requests the necessary permissions and gracefully handles permission requests, as this is critical for user experience.
0 Comments