9
0
mirror of https://gitee.com/shuto/customCamera.git synced 2026-05-02 00:07:24 +08:00

- Refacto & comments code.

- Normalisation error message for js.
- Manage back button.
- Managa unavailable camera.
This commit is contained in:
Christophe BOUCAUT
2014-11-21 15:50:38 +01:00
parent 383b8feaaf
commit eebbc0d225
15 changed files with 643 additions and 568 deletions
+56 -15
View File
@@ -1,11 +1,12 @@
package org.geneanet.customcamera;
import XXX_NAME_CURRENT_PACKAGE_XXX.CameraView;
import XXX_NAME_CURRENT_PACKAGE_XXX.CameraActivity;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
@@ -22,17 +23,23 @@ public class CameraLauncher extends CordovaPlugin {
protected CallbackContext callbackContext;
protected static final int RESULT_SUCCESS = 1;
protected static final int RESULT_ERROR = 2;
protected static final int RESULT_BACK = 3;
protected static final int REQUEST_CODE = 88224646;
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("startCamera")) {
this.callbackContext = callbackContext;
Intent intent = new Intent(this.cordova.getActivity(), CameraView.class);
Intent intent = new Intent(this.cordova.getActivity(), CameraActivity.class);
Bundle imgBackgroundBase64 = new Bundle();
imgBackgroundBase64.putString("imgBackgroundBase64", args.getString(0));
intent.putExtras(imgBackgroundBase64);
cordova.startActivityForResult((CordovaPlugin) this, intent, 123456789);
cordova.startActivityForResult((CordovaPlugin) this, intent, CameraLauncher.REQUEST_CODE);
return true;
}
@@ -41,19 +48,41 @@ public class CameraLauncher extends CordovaPlugin {
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 123456789 && resultCode == 1) {
String pathPicture = intent.getStringExtra("pathPicture");
// Log.d("customCamera", pathPicture);
try {
File fl = new File(pathPicture);
byte[] ret = loadFile(fl);
if (requestCode == CameraLauncher.REQUEST_CODE) {
switch (resultCode)
{
case CameraLauncher.RESULT_ERROR:
this.callbackContext.error(
generateError(
CameraLauncher.RESULT_ERROR,
intent.getStringExtra("errorMessage")
)
);
break;
case CameraLauncher.RESULT_BACK:
this.callbackContext.error(
generateError(
CameraLauncher.RESULT_BACK,
"Error because back camera."
)
);
break;
case CameraLauncher.RESULT_SUCCESS:
String pathPicture = intent.getStringExtra("pathPicture");
try {
File fl = new File(pathPicture);
byte[] ret = loadFile(fl);
byte[] output = Base64.encode(ret, Base64.NO_WRAP);
String js_out = new String(output);
this.callbackContext.success(js_out);
} catch (Exception e) {
this.callbackContext.error("Error to get content file.");
byte[] output = Base64.encode(ret, Base64.NO_WRAP);
String js_out = new String(output);
this.callbackContext.success(js_out);
} catch (Exception e) {
this.callbackContext.error("Error to get content file.");
}
break;
default:
this.callbackContext.error("Camera has crashed.");
}
}
}
@@ -78,4 +107,16 @@ public class CameraLauncher extends CordovaPlugin {
is.close();
return bytes;
}
protected JSONObject generateError(int code, String message) {
JSONObject resultForPlugin = new JSONObject();
try {
resultForPlugin.put("code", code);
resultForPlugin.put("message", message);
} catch (JSONException e) {
e.printStackTrace();
}
return resultForPlugin;
}
}
+2 -2
View File
@@ -28,8 +28,8 @@
</intent-filter>
</activity>
<activity
android:name="org.geneanet.customcamera.CameraView"
android:label="@string/title_activity_camera_view"
android:name="org.geneanet.customcamera.CameraActivity"
android:label="@string/title_activity_camera_activity"
android:screenOrientation="fullSensor">
</activity>
@@ -83,17 +83,18 @@
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:alpha="0.6"
android:background="@color/black" >
android:background="@color/black"
android:visibility="invisible" >
<Button
android:id="@+id/accepter"
android:id="@+id/accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Accepter photo" />
<Button
android:id="@+id/refuser"
android:id="@+id/decline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
@@ -1,11 +0,0 @@
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="org.geneanet.testcustomcamera.CameraView" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>
@@ -4,7 +4,7 @@
<string name="app_name">TestCustomCamera</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="title_activity_camera_view">CameraViewNative</string>
<string name="title_activity_camera_activity">CameraActivityNative</string>
<string name="start_custom_camera">Start Custom Camera</string>
<string name="capture">Capture</string>
<string name="todo">TODO</string>
@@ -0,0 +1,399 @@
package org.geneanet.customcamera;
// DON'T DELETE THIS LINE, IT'S NECESSARY FOR THE CORDOVA PLUGIN.
import org.geneanet.customcamera.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import android.util.Log;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
/**
* Activity to use customCamera.
*/
public class CameraActivity extends Activity {
/**
* Enable miniature mode.
*/
private boolean modeMiniature = false;
/**
* Camera resource.
*/
private Camera mCamera = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Remove title bar */
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
/* Remove notification bar */
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera_view);
// Get the base64 picture for the background only if it's exist.
Bundle currentBundle = this.getIntent().getExtras();
if (currentBundle != null) {
String imgBackgroundBase64 = currentBundle.getString("imgBackgroundBase64");
}
// Get informations about the default display for the device
Display defaultDisplay = getWindowManager().getDefaultDisplay();
// Init camera resource.
if (!initCameraResource()) {
return;
}
// Get the default orientation of the device
int defaultOrientation = getDeviceDefaultOrientation();
// Change camera orientation function of the device's default orientation.
if (defaultOrientation == 1 || defaultOrientation == 2) {
int orientation;
switch(defaultDisplay.getRotation()){
case 0 :
orientation = (defaultOrientation == 1) ? 90 : 0;
mCamera.setDisplayOrientation(orientation);
break;
case 1 :
orientation = (defaultOrientation == 1) ? 0 : 270;
mCamera.setDisplayOrientation(orientation);
break;
case 2 :
orientation = (defaultOrientation == 1) ? 270 : 180;
mCamera.setDisplayOrientation(orientation);
break;
case 3 :
orientation = (defaultOrientation == 1) ? 180 : 90;
mCamera.setDisplayOrientation(orientation);
break;
}
}
// Assign the render camera to the view
CameraPreview mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// The opacity bar
SeekBar switchOpacity = (SeekBar) findViewById(R.id.switchOpacity);
// Event on change opacity.
switchOpacity.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int progress = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
progress = progresValue;
ImageView imageView = (ImageView) findViewById(R.id.normal);
float newOpacity = (float) (0.2+progress*0.1);
imageView.setAlpha(newOpacity);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
}
// Event on touch screen to call the manager of the zoom & the auto focus.
@Override
public boolean onTouchEvent(MotionEvent event) {
Camera.Parameters params = mCamera.getParameters();
int action = event.getAction();
if (event.getPointerCount() > 1) {
// If we touch with more than one finger
float distanceBetweenFingers = 0;
if (action == MotionEvent.ACTION_POINTER_UP) {
distanceBetweenFingers = getFingerSpacing(event);
} else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {
mCamera.cancelAutoFocus();
handleZoom(event, params, distanceBetweenFingers);
}
} else {
// If we touch with one finger -> auto-focus
if (action == MotionEvent.ACTION_UP) {
handleFocus(event, params);
}
}
return true;
}
/**
* Manage the zoom.
*
* @param MotionEvent event Current event which start this action.
* @param Parameters params Camera's parameter.
* @param float distanceBetweenFingers Distance between two fingers.
*/
private void handleZoom(MotionEvent event, Camera.Parameters params, float distanceBetweenFingers) {
// take zoom max for the camera hardware.
int maxZoom = params.getMaxZoom();
// current value for the zoom.
int zoom = params.getZoom();
// new distance between fingers.
float newDist = getFingerSpacing(event);
if (newDist > distanceBetweenFingers) {
//zoom in
if (zoom < maxZoom/2)
zoom+=2;
} else if (newDist < distanceBetweenFingers) {
//zoom out
if (zoom > 0)
zoom-=2;
}
distanceBetweenFingers = newDist;
params.setZoom(zoom);
mCamera.setParameters(params);
}
/**
* Manage the focus.
*
* @param MotionEvent event Current event which start this action.
* @param Parameters params Camera's parameter.
*/
public void handleFocus(MotionEvent event, Camera.Parameters params) {
List<String> supportedFocusModes = params.getSupportedFocusModes();
if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean b, Camera camera) {}
});
}
}
/**
* Determine the space between the first two fingers.
*
* @param MotionEvent event Current event which start this calculation.
*
* @return float
*/
private float getFingerSpacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
/**
* Display the miniature.
* @param View view Current view.
*/
public void showMiniature(View view) {
// Picture for the background.
final ImageView imageView = (ImageView) findViewById(R.id.normal);
// Button for show miniature picture.
final Button miniature = (Button) view;
// if it's not miniature mode.
if (!modeMiniature) {
modeMiniature = true;
// Set new size for miniature layout.
FrameLayout.LayoutParams paramsMiniature = new FrameLayout.LayoutParams(imageView.getWidth()/4, imageView.getHeight()/4);
paramsMiniature.gravity = Gravity.BOTTOM;
imageView.setLayoutParams(paramsMiniature);
// Set current opacity for the miniature.
// imageView.setAlpha(imageView.getAlpha());
// Hide the miniature button.
miniature.setVisibility(View.INVISIBLE);
// Add event on click action for the miniature picture.
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
modeMiniature = false;
// resize miniature.
LayoutParams paramsReagrandissement = (LayoutParams) imageView.getLayoutParams();
paramsReagrandissement.width = -1;
paramsReagrandissement.height = -1;
imageView.setLayoutParams(paramsReagrandissement);
// imageView.setAlpha(imageView.getAlpha());
miniature.setVisibility(View.VISIBLE);
}
});
}
}
/**
* Method to destroy the view (here, the activity).
*/
protected void onDestroy() {
super.onDestroy();
ManagerCamera.clearCameraAccess();
}
/**
* Method to apply the new view after rotation.
*/
protected void onResume(){
super.onResume();
}
/**
* Method to get the device default orientation.
*
* @return int
*/
public int getDeviceDefaultOrientation() {
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Configuration config = getResources().getConfiguration();
int rotation = windowManager.getDefaultDisplay().getRotation();
if (
(config.orientation == Configuration.ORIENTATION_LANDSCAPE &&
(
rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180
)
) ||
(config.orientation == Configuration.ORIENTATION_PORTRAIT &&
(
rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270
)
)
) {
return Configuration.ORIENTATION_LANDSCAPE;
} else {
return Configuration.ORIENTATION_PORTRAIT;
}
}
/**
* Method to take picture.
*
* @param view Current view.
*/
public void takePhoto(View view) {
final CameraActivity cameraActivityCurrent = this;
// Handles the moment where picture is taken
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {}
};
// Handles data for raw picture
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {}
};
// Handles data for jpeg picture
PictureCallback jpegCallback = new PictureCallback() {
/**
* Event when picture is taken.
*
* @param byte[] data Picture with byte format.
* @param Camera camera Current resource camera.
*/
public void onPictureTaken(final byte[] data, Camera camera) {
// Show buttons to accept or decline the picture.
final LinearLayout keepPhoto = (LinearLayout) findViewById(R.id.keepPhoto);
keepPhoto.setVisibility(View.VISIBLE);
Button accept = (Button)findViewById(R.id.accept);
Button decline = (Button)findViewById(R.id.decline);
// Hide the capture button.
final Button photo = (Button)findViewById(R.id.capture);
photo.setVisibility(View.INVISIBLE);
// Stop link between view and camera to start the preview picture.
mCamera.stopPreview();
// Event started after accept picture.
accept.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
// Get path picture to storage.
String pathPicture = Environment.getExternalStorageDirectory().getPath()+"/"+Environment.DIRECTORY_DCIM+"/Camera/";
pathPicture = pathPicture+String.format("%d.jpeg", System.currentTimeMillis());
// Write data in file.
FileOutputStream outStream = new FileOutputStream(pathPicture);
outStream.write(data);
outStream.close();
// Return to success & finish current activity.
cameraActivityCurrent.setResult(1, new Intent().putExtra("pathPicture", pathPicture));
cameraActivityCurrent.finish();
} catch (IOException e) {
e.printStackTrace();
}
}
});
// Event started after decline picture.
decline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
keepPhoto.setVisibility(View.INVISIBLE);
photo.setVisibility(View.VISIBLE);
mCamera.startPreview();
}
});
};
};
// Start capture picture.
mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
/**
* To get camera resource or stop this activity.
*
* @return boolean
*/
protected boolean initCameraResource()
{
mCamera = ManagerCamera.getCameraInstance();
if (mCamera == null) {
this.setResult(2, new Intent().putExtra("errorMessage", "Camera is unavailable."));
this.finish();
return false;
}
return true;
}
@Override
public void onBackPressed() {
this.setResult(3);
this.finish();
}
}
@@ -8,62 +8,73 @@ import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Interface between the view and the camera.
*/
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
/**
* Constructor
* @override
*/
public CameraPreview(Context context, Camera camera) {
super(context);
// assign camera
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
/******************************/
/** WHEN THE VIEW IS CREATED **/
/******************************/
/**
* When the view is created.
* @param SurfaceHolder holder
*/
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewCallback(null);
try {
// Reset preview start camera.
mCamera.setPreviewCallback(null);
mCamera.setPreviewDisplay(holder);
// Start link between the view and the camera.
mCamera.startPreview();
} catch (IOException e) {
mCamera.release();
mCamera = null;
Log.d("error", "Error setting camera preview: " + e.getMessage());
mCamera.release();
mCamera = null;
Log.e("customCamera", "Error setting camera preview: " + e.getMessage());
}
}
/******************************/
/** WHEN THE VIEW IS CHANGED **/
/******************************/
/**
* When the view is changed.
* @override.
*/
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// check if the surface exist.
if (mHolder.getSurface() == null){
return;
return;
}
try {
mCamera.setPreviewCallback(null);
// stop current instance.
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
} catch (Exception e){}
} catch (Exception e) {}
try {
// Start new link between the view and the camera.
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
} catch (Exception e) {
Log.d("error", "Error starting camera preview: " + e.getMessage());
}
}
/*******************************************/
/** TO DESTROY THE SURFACE OF THE PREVIEW **/
/*******************************************/
public void surfaceDestroyed(SurfaceHolder holder) {
if(mCamera!=null){
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera = null;
}
}
/**
* To destroy the surface of the preview.
* @override
*/
public void surfaceDestroyed(SurfaceHolder holder) {}
}
@@ -1,367 +0,0 @@
package org.geneanet.customcamera;
// Don't delete this line
import org.geneanet.customcamera.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.content.Intent;
//import android.media.AudioManager;
//import android.media.MediaPlayer;
//import android.media.SoundPool;
import android.os.Bundle;
import android.os.Environment;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class CameraView extends Activity {
private float mDist;
private int modeMiniature = 0;
private CameraPreview mPreview;
static boolean clickOn = false;
private static Camera mCamera = null;
public static final int MEDIA_TYPE_IMAGE = 1;
// private SoundPool sounds;
// private int sSound;
FileOutputStream outStream = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
Bundle currentBundle = this.getIntent().getExtras();
if (currentBundle != null) {
String imgBackgroundBase64 = currentBundle.getString("imgBackgroundBase64");
new AlertDialog.Builder(this)
.setTitle("Delete entry")
.setMessage(imgBackgroundBase64)
.show();
}
super.onCreate(savedInstanceState);
/* Remove title bar */
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
/* Remove notification bar */
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera_view);
/* Get informations about the device */
Display display = getWindowManager().getDefaultDisplay();
/* Get object which use the camera and orient it in function of the screen */
mCamera = CustomCamera.getCameraInstance();
/* Hide the accept/refuse photo interface */
LinearLayout keepPhoto = (LinearLayout)findViewById(R.id.keepPhoto);
keepPhoto.setVisibility(View.INVISIBLE);
/* Get the default orientation of the device */
int defaultOrientation = getDeviceDefaultOrientation();
if (defaultOrientation == 1){ // We are in portrait orientation
System.out.println(display.getRotation());
switch(display.getRotation()){
case 0 :
mCamera.setDisplayOrientation(90);
break;
case 1 :
mCamera.setDisplayOrientation(0);
break;
case 2 :
mCamera.setDisplayOrientation(270);
break;
case 3 :
mCamera.setDisplayOrientation(180);
break;
}
}
if (defaultOrientation == 2){ // We are in landscape orientation
switch(display.getRotation()){
case 0 :
mCamera.setDisplayOrientation(0);
break;
case 1 :
mCamera.setDisplayOrientation(270);
break;
case 2 :
mCamera.setDisplayOrientation(180);
break;
case 3 :
mCamera.setDisplayOrientation(90);
break;
}
}
/* Assign the render to the view */
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
/* The opacity bar */
SeekBar switchOpacity = (SeekBar) findViewById(R.id.switchOpacity);
switchOpacity.setOnSeekBarChangeListener(
new OnSeekBarChangeListener() {
int progress = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
progress = progresValue;
ImageView imageView = (ImageView) findViewById(R.id.normal);
float newOpacity = (float) (0.2+progress*0.1);
imageView.setAlpha(newOpacity);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
}
/*******************************************************/
/** BLOCK THE ROTATION IN FUNCTION OF THE POSTAL CARD **/
/*******************************************************/
// @Override
// public void onWindowFocusChanged(boolean hasFocus){
//
// ImageView imageView = (ImageView) findViewById(R.id.normal);
// int widthImage=imageView.getWidth();
// int heightImage=imageView.getHeight();
//
// if(heightImage < widthImage || imageView.getRotation() != 0){
// this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// imageView.setRotation(0);
// }
// else{
// this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// }
// }
/******************/
/** FOR THE ZOOM **/
/******************/
@Override
public boolean onTouchEvent(MotionEvent event) {
Camera.Parameters params = mCamera.getParameters();
int action = event.getAction();
if (event.getPointerCount() > 1) {
// If we touch with more than one finger
if (action == MotionEvent.ACTION_POINTER_UP) {
mDist = getFingerSpacing(event);
} else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {
mCamera.cancelAutoFocus();
handleZoom(event, params, mDist);
}
} else {
// If we touch with one finger -> auto-focus
if (action == MotionEvent.ACTION_UP) {
handleFocus(event, params);
}
}
return true;
}
/*********************/
/** MANAGE THE ZOOM **/
/*********************/
private void handleZoom(MotionEvent event, Camera.Parameters params, float mDist) {
int maxZoom = params.getMaxZoom();
int zoom = params.getZoom();
float newDist = getFingerSpacing(event);
if (newDist > mDist) {
//zoom in
if (zoom < maxZoom/2)
zoom+=2;
} else if (newDist < mDist) {
//zoom out
if (zoom > 0)
zoom-=2;
}
mDist = newDist;
params.setZoom(zoom);
mCamera.setParameters(params);
}
/**********************/
/** MANAGE THE FOCUS **/
/**********************/
public void handleFocus(MotionEvent event, Camera.Parameters params) {
List<String> supportedFocusModes = params.getSupportedFocusModes();
if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean b, Camera camera) {}
});
}
}
/*******************************************************/
/** DETERMINE THE SPACE BETWEEN THE FIRST TWO FINGERS **/
/*******************************************************/
private float getFingerSpacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
/***************************/
/** DISPLAY THE MINIATURE **/
/***************************/
public void showMiniature(View view){
ImageView imageView = (ImageView) findViewById(R.id.normal);
Button miniature = (Button) findViewById(R.id.miniature);
if(modeMiniature == 0){
FrameLayout.LayoutParams paramsMiniature = new FrameLayout.LayoutParams(imageView.getWidth()/4, imageView.getHeight()/4);
paramsMiniature.gravity=Gravity.BOTTOM;
imageView.setAlpha(imageView.getAlpha());
modeMiniature = 1;
imageView.setLayoutParams(paramsMiniature);
miniature.setEnabled(false);
miniature.setVisibility(View.INVISIBLE);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView imageView = (ImageView) findViewById(R.id.normal);
Button miniature = (Button) findViewById(R.id.miniature);
LayoutParams paramsReagrandissement = (LayoutParams) imageView.getLayoutParams();
paramsReagrandissement.width = -1;
paramsReagrandissement.height = -1;
imageView.setAlpha(imageView.getAlpha());
modeMiniature = 0;
imageView.setLayoutParams(paramsReagrandissement);
miniature.setVisibility(View.VISIBLE);
miniature.setEnabled(true);
}
});
}
}
/*****************************************************/
/** METHOD TO DESTROY THE VIEW (HERE, THE ACTIVITY) **/
/*****************************************************/
protected void onDestroy() {
super.onDestroy();
CustomCamera.clearCameraAccess();
}
/*************************************************/
/** METHOD TO APPLY THE NEW VIEW AFTER ROTATION **/
/*************************************************/
protected void onResume(){
super.onResume();
}
/**************************************************/
/** METHOD TO GET THE DEVICE DEFAULT ORIENTATION **/
/**************************************************/
public int getDeviceDefaultOrientation() {
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Configuration config = getResources().getConfiguration();
int rotation = windowManager.getDefaultDisplay().getRotation();
if ( ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) &&
config.orientation == Configuration.ORIENTATION_LANDSCAPE)
|| ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) &&
config.orientation == Configuration.ORIENTATION_PORTRAIT)) {
return Configuration.ORIENTATION_LANDSCAPE;
} else {
return Configuration.ORIENTATION_PORTRAIT;
}
}
/****************************/
/** METHOD TO TAKE PICTURE **/
/****************************/
public void takePhoto(View view){
final CameraView cameraViewCurrent = this;
/** To custom sound when you shot with the camera - optionnal**/
// sounds = new SoundPool(10, AudioManager.STREAM_MUSIC,0);
// sSound = sounds.load(this.getApplicationContext(), R.raw.r2d2, 1);
/** Handles the moment where picture is taken **/
final ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
// sounds.play(sSound, 1.0f, 1.0f, 0, 0, 1.0f);
// sounds.setVolume(1, (float)0.4, (float)0.4);
}
};
/** Handles data for raw picture **/
final PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {}
};
/** Handles data for jpeg picture **/
final PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(final byte[] data, Camera camera) {
final LinearLayout keepPhoto = (LinearLayout)findViewById(R.id.keepPhoto);
keepPhoto.setVisibility(View.VISIBLE);
Button refuser = (Button)findViewById(R.id.refuser);
Button accepter = (Button)findViewById(R.id.accepter);
final Button photo = (Button)findViewById(R.id.capture);
// Button miniature = (Button)findViewById(R.id.miniature);
photo.setVisibility(View.INVISIBLE);
mCamera.stopPreview();
accepter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String pathPicture = Environment.getExternalStorageDirectory().getPath()+"/"+Environment.DIRECTORY_DCIM+"/Camera/";
pathPicture = pathPicture+String.format("%d.jpeg", System.currentTimeMillis());
outStream = new FileOutputStream(pathPicture);
outStream.write(data);
outStream.close();
cameraViewCurrent.setResult(1, new Intent().putExtra("pathPicture", pathPicture));
cameraViewCurrent.finish();
} catch (IOException e) {
e.printStackTrace();
}
}
});
refuser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
keepPhoto.setVisibility(View.INVISIBLE);
photo.setVisibility(View.VISIBLE);
mCamera.startPreview();
}
});
};
};
mCamera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
}
@@ -1,44 +0,0 @@
package org.geneanet.customcamera;
import android.hardware.Camera;
public class CustomCamera {
protected static Camera mCamera = null;
// constantes sur les orientations de téléphones.
public final static int PORTRAIT = 0;
public final static int LANDSCAPE = 1;
public final static int PORTRAIT_INVERSED = 2;
public final static int LANDSCAPE_INVERSED = 3;
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
// si on a déjà une camera récupérée dans l'application, on la retourne directement.
if (CustomCamera.mCamera != null) {
return mCamera;
}
// si non, on va chercher la camera de derrière.
Camera c = null;
try {
c = Camera.open(0); // attempt to get a Camera instance
System.out.println(c.getParameters().toString());
}
catch (RuntimeException e){
// Camera is not available (in use or does not exist)
System.err.println("rt"+e);
}
CustomCamera.mCamera = c;
return c; // returns null if camera is unavailable
}
public static void clearCameraAccess() {
if (CustomCamera.mCamera != null) {
CustomCamera.mCamera.stopPreview();
// CustomCamera.mCamera.release();
CustomCamera.mCamera = null;
}
}
}
@@ -8,61 +8,38 @@ import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import android.view.View;
/**
* Just to test application.
*/
public class MainActivity extends Activity {
Camera mCamera;
Camera mCamera;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Enfin, on lance l'intent pour que l'application de photo se lance
// startActivityForResult(intent, 42);
}
public void startCamera(View view) {
if(this.checkCameraHardware(this)){
Intent intent = new Intent(this, CameraView.class);
if(this.checkCameraHardware(this)){
Intent intent = new Intent(this, CameraActivity.class);
startActivity(intent);
finish();
}
else {
System.out.println("NO");
}
}
else {
Log.d("customCamera", "No camera hardware detected.");
}
}
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA) || Camera.getNumberOfCameras() > 0){
// this device has a camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA) || Camera.getNumberOfCameras() > 0) {
return true;
} else {
// no camera on this device
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
@@ -0,0 +1,52 @@
package org.geneanet.customcamera;
import android.hardware.Camera;
import android.util.Log;
/**
* Manage camera resource.
*/
public class ManagerCamera {
protected static Camera mCamera = null;
// Constant to define differents orientations for the devices.
public final static int PORTRAIT = 0;
public final static int LANDSCAPE = 1;
public final static int PORTRAIT_INVERSED = 2;
public final static int LANDSCAPE_INVERSED = 3;
/**
* A safe way to get an instance of the Camera object.
* @return Camera | null
*/
public static Camera getCameraInstance(){
// If camera is already instanced and available, return this resource.
if (ManagerCamera.mCamera != null) {
return mCamera;
}
// Start back camera.
Camera c = null;
try {
c = Camera.open(0);
}
catch (RuntimeException e) {
Log.d("customCamera", "Can't open the camera.");
}
ManagerCamera.mCamera = c;
return c; // returns null if camera is unavailable
}
/**
* To release the camera.
*/
public static void clearCameraAccess() {
if (ManagerCamera.mCamera != null) {
ManagerCamera.mCamera.stopPreview();
ManagerCamera.mCamera.release();
ManagerCamera.mCamera = null;
}
}
}
@@ -6,58 +6,60 @@ import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.SeekBar;
/**
* Widget for opacity bar.
*/
public class VerticalSeekBar extends SeekBar {
/**
* Constructor
* @override
*/
public VerticalSeekBar(Context context) {
super(context);
}
public VerticalSeekBar(Context context) {
super(context);
}
public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public VerticalSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VerticalSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(h, w, oldh, oldw);
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(h, w, oldh, oldw);
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
protected void onDraw(Canvas c) {
c.rotate(-90);
c.translate(-getHeight(), 0);
super.onDraw(c);
}
protected void onDraw(Canvas c) {
c.rotate(-90);
c.translate(-getHeight(), 0);
super.onDraw(c);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
onSizeChanged(getWidth(), getHeight(), 0, 0);
break;
case MotionEvent.ACTION_CANCEL:
break;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
onSizeChanged(getWidth(), getHeight(), 0, 0);
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
return true;
}
}