01.안드로이드 미디어 프로그래밍(빛과 소리의 향연) : 투에이치앤에스 : 박헌재 지음 : https://cafe.naver.com/webdroid < 소스코드
02.안드로이드 프로그래밍 입문+활용 : 앤써북 : 정동근지음 : http://cafe.naver.com/tizenity ( [부록CD/도서자료/정오표]-도서 부록CD] 게시판) / topofsan@hotmail.com
03.실전앱프로젝트 안드로이드게임개발편 : 제이펍 : 박승제지음 안드로이드사이드 게임강사 : 프로젝트 파일 다운로드 : http://book.androidside.com / foxmann@naver.com / http://foxmann.blog.me
04.안드로이드 게임개발의 정석 : 제이펍 : 박승제지음 : https://github.com/foxmann/Android, https://github.com/Jbub/AndroidGameBible / foxmann@naver.com / readers.jpub@gmail.com
05.프로그래머를 위한 안드로이드 : 안드로이드 앱 중심 접근법 : 실제 애플리케이션의 전체 코드로 배우는 진짜 안드로이드 앱 개발 : www.deitel.com / deitel@deitel.com / Welcome 앱, 계산기앱, 트위터 검색앱, 국기 맞추기 앱
06.예제가 가득한 Android 프로그래밍 Android 앱 개발자들을 만족시킨 239가지 최고의 레시피 : www.infopub.co.kr < 자료실
https://inducesmile.com/android/android-camera2-api-example-tutorial/
참고
# https://developer.android.com/guide/topics/media/camera#java
- https://github.com/googlesamples/android-Camera2Basic/
- https://github.com/googlesamples/android-Camera2Raw/
# https://android-arsenal.com/details/1/6575
- https://github.com/siralam/CameraViewPlus.git
- https://github.com/google/cameraview.git
- https://github.com/RedApparat/Fotoapparat.git
https://github.com/almalence/OpenCamera.git
https://github.com/memfis19/Annca/issues/30
https://github.com/memfis19/Annca.git
Detect and Access Camera
Create code to check for the existence of cameras and request access.
( 카메라 가 있는지 확인하고 액세스를 요청하는 코드를 만듭니다.)Detecting camera hardware - Camera.getNumberOfCameras()
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){ // this device has a camera return true; } else { // no camera on this device return false; }
}
Accessing cameras - Camera.open()
/** 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
}
Checking camera features
- Camera.getParameters()
- Camera.Parameters
- Camera.getCameraInfo()
Create a Preview Class
Create a camera preview class that extends SurfaceView and implements the SurfaceHolder interface. This class previews the live images from the camera.
( 인터페이스 를 확장 SurfaceView하고 구현 하는 카메라 미리보기 클래스를 만듭니다 SurfaceHolder. 이 클래스는 카메라의 라이브 이미지를 미리 봅니다.)Creating a preview class - getSupportedPreviewSizes(), setPreviewSize()
/** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {private SurfaceHolder mHolder; private Camera mCamera; public CameraPreview(Context context, Camera camera) { super(context); mCamera = camera; // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); // deprecated setting, but required on Android versions prior to 3.0 mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, now tell the camera where to draw the preview. try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { Log.d(TAG, "Error setting camera preview: " + e.getMessage()); } } public void surfaceDestroyed(SurfaceHolder holder) { // empty. Take care of releasing the Camera preview in your activity. } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // If your preview can change or rotate, take care of those events here. // Make sure to stop the preview before resizing or reformatting it. if (mHolder.getSurface() == null){ // preview surface does not exist return; } // stop preview before making changes try { mCamera.stopPreview(); } catch (Exception e){ // ignore: tried to stop a non-existent preview } // set preview size and make any resize, rotate or // reformatting changes here // start preview with new settings try { mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e){ Log.d(TAG, "Error starting camera preview: " + e.getMessage()); } }
}
Build a Preview Layout
Once you have the camera preview class, create a view layout that incorporates the preview and the user interface controls you want.
( 일단 카메라 미리보기 클래스가 있으면 원하는 미리보기와 사용자 인터페이스 컨트롤을 통합하는 뷰 레이아웃을 만듭니다. )Placing preview in a layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" > <FrameLayout android:id="@+id/camera_preview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> <Button android:id="@+id/button_capture" android:text="Capture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" />
<activity android:name=".CameraActivity"
android:label="@string/app_name" android:screenOrientation="landscape"> <!-- configure this activity to use landscape orientation --> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>
public class CameraActivity extends Activity {
private Camera mCamera; private CameraPreview mPreview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create an instance of Camera mCamera = getCameraInstance(); // Create our Preview view and set it as the content of our activity. mPreview = new CameraPreview(this, mCamera); FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview); preview.addView(mPreview); }
}
Setup Listeners for Capture
- Connect listeners for your interface controls to start image or video capture in response to user actions, such as pressing a button.
( 단추를 누르는 것과 같은 사용자 작업에 응답하여 이미지 컨트롤이나 비디오 캡처를 시작하기 위해 인터페이스 컨트롤의 리스너를 연결합니다. )
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
}@Override public void onClick(View v) { // get an image from the camera mCamera.takePicture(null, null, mPicture); }
);
- Connect listeners for your interface controls to start image or video capture in response to user actions, such as pressing a button.
Capture and Save Files
Setup the code for capturing pictures or videos and saving the output.
( 사진 또는 비디오 캡처 및 출력 저장을위한 코드를 설정합니다. )Capturing pictures - Camera.takePicture(), Camera.PictureCallback
private PictureCallback mPicture = new PictureCallback() {
@Override public void onPictureTaken(byte[] data, Camera camera) { File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); if (pictureFile == null){ Log.d(TAG, "Error creating media file, check storage permissions"); return; } try { FileOutputStream fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); } catch (FileNotFoundException e) { Log.d(TAG, "File not found: " + e.getMessage()); } catch (IOException e) { Log.d(TAG, "Error accessing file: " + e.getMessage()); } }
};
Release the Camera
After using the camera, your application must properly release it for use by other applications.
( 카메라를 사용한 후에는 응용 프로그램이 다른 응용 프로그램에서 사용할 수 있도록 제대로 릴리스해야합니다. )Releasing the camera - Activity.onPause(), Camera.release()
public class CameraActivity extends Activity {
private Camera mCamera; private SurfaceView mPreview; private MediaRecorder mMediaRecorder; ... @Override protected void onPause() { super.onPause(); releaseMediaRecorder(); // if you are using MediaRecorder, release it first releaseCamera(); // release the camera immediately on pause event } private void releaseMediaRecorder(){ if (mMediaRecorder != null) { mMediaRecorder.reset(); // clear recorder configuration mMediaRecorder.release(); // release the recorder object mMediaRecorder = null; mCamera.lock(); // lock camera for later use } } private void releaseCamera(){ if (mCamera != null){ mCamera.release(); // release the camera for other applications mCamera = null; } }
}
============ ============ ============ ============ ============
Camera features
- Metering and focus areas
- Face detection
- Time lapse video
============================== ============ ===================================================================================================
Feature API Level Description
============================== ============ ===================================================================================================
Face Detection 14 Identify human faces within a picture and use them for focus, metering and white balance
Metering Areas 14 Specify one or more areas within an image for calculating white balance
Focus Areas 14 Set one or more areas within an image to use for focus
White Balance Lock 14 Stop or start automatic white balance adjustments
Exposure Lock 14 Stop or start automatic exposure adjustments
Video Snapshot 14 Take a picture while shooting video (frame grab)
Time Lapse Video 11 Record frames with set delays to record a time lapse video
Multiple Cameras 9 Support for more than one camera on a device, including front-facing and back-facing cameras
Focus Distance 9 Reports distances between the camera and objects that appear to be in focus
Zoom 8 Set image magnification
Exposure Compensation 8 Increase or decrease the light exposure level
GPS Data 5 Include or omit geographic location data with the image
White Balance 5 Set the white balance mode, which affects color values in the captured image
Focus Mode 5 Set how the camera focuses on a subject such as automatic, fixed, macro or infinity
Scene Mode 5 Apply a preset mode for specific types of photography situations such as night, beach, snow or candlelight scenes
JPEG Quality 5 Set the compression level for a JPEG image, which increases or decreases image output file quality and size
Flash Mode 5 Turn flash on, off, or use automatic setting
Color Effects 5 Apply a color effect to the captured image such as black and white, sepia tone or negative.
Anti-Banding 5 Reduces the effect of banding in color gradients due to JPEG compression
Picture Format 1 Specify the file format for the picture
Picture Size 1 Specify the pixel dimensions of the saved picture
============================== ============ ===================================================================================================
# Checking feature availability
// get Camera parameters
Camera.Parameters params = mCamera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
// Autofocus mode is supported
}
# Using camera features
// get Camera parameters
Camera.Parameters params = mCamera.getParameters();
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// set Camera parameters
mCamera.setParameters(params);
# Metering and focus areas
// Create an instance of Camera
mCamera = getCameraInstance();
// set Camera parameters
Camera.Parameters params = mCamera.getParameters();
if (params.getMaxNumMeteringAreas() > 0){ // check that metering areas are supported
List<Camera.Area> meteringAreas = new ArrayList<Camera.Area>();
Rect areaRect1 = new Rect(-100, -100, 100, 100); // specify an area in center of image
meteringAreas.add(new Camera.Area(areaRect1, 600)); // set weight to 60%
Rect areaRect2 = new Rect(800, -1000, 1000, -800); // specify an area in upper right of image
meteringAreas.add(new Camera.Area(areaRect2, 400)); // set weight to 40%
params.setMeteringAreas(meteringAreas);
}
mCamera.setParameters(params);
# Face detection
class MyFaceDetectionListener implements Camera.FaceDetectionListener {
@Override
public void onFaceDetection(Face[] faces, Camera camera) {
if (faces.length > 0){
Log.d("FaceDetection", "face detected: "+ faces.length +
" Face 1 Location X: " + faces[0].rect.centerX() +
"Y: " + faces[0].rect.centerY() );
}
}
}
mCamera.setFaceDetectionListener(new MyFaceDetectionListener());
public void startFaceDetection(){
// Try starting Face Detection
Camera.Parameters params = mCamera.getParameters();
// start face detection only *after* preview has started
if (params.getMaxNumDetectedFaces() > 0){
// camera supports face detection, so can start it:
mCamera.startFaceDetection();
}
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
startFaceDetection(); // start face detection feature
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (holder.getSurface() == null){
// preview surface does not exist
Log.d(TAG, "holder.getSurface() == null");
return;
}
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
Log.d(TAG, "Error stopping camera preview: " + e.getMessage());
}
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
startFaceDetection(); // re-start face detection feature
} catch (Exception e){
// ignore: tried to stop a non-existent preview
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
댓글