How to Integrate and Embrace The Power of Android Camera API

0
Shares
How to Integrate and Embrace The Power of Android Camera API
4.8 (95%) 4 votes

The latest apps these days offer their users to take pictures and record videos using camera of mobile phones for several purposes. But to use this cameras of Android phones in your Android app, you need to integrate Android Camera API.

Now this integration of Android Camera API can be done in 2 ways. The first way requires to use Android inbuilt camera app, which is an easy process. However, doing so won’t offer much control over the camera of Android phone as it will taken care by the inbuilt camera app.

The second way is by building a custom interface in your Android app and adding your desired functionalities. Now of course this will demand higher efforts than the first way as you’ll be doing everything on your own. But the plus point is, you’ll be able to offer much more functionalities in your Android app if you decide to integrate Android Camera API the second way.

In today’s Android camera tutorial, we’ll build a sample app to demonstrate the integration of Android Camera API with one Android camera example.

Let’s Get Started

Extend SurfaceView

to load camera in activity extend surfaceview.

  • Set basic camera in activity extend surfaceview
private SurfaceHolder mHolder;
protected Camera mCamera;

protected List<Camera.Size> mPreviewSizeList;

protected List<Camera.Size> mPictureSizeList;

protected Camera.Size mPreviewSize;

protected Camera.Size mPictureSize;

public CamPreview(Activity activity, int cameraId, LayoutMode mode) {

super(activity); // Always necessary

mActivity = activity;

mLayoutMode = mode;

mHolder = getHolder();

mHolder.addCallback(this);

mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {

if (Camera.getNumberOfCameras() > cameraId) {

mCameraId = cameraId;

} else {

mCameraId = 0;

}

} else {

mCameraId = 0;

}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {

mCamera = Camera.open(mCameraId);

} else {

mCamera = Camera.open();

}

Camera.Parameters cameraParams = mCamera.getParameters();

mPreviewSizeList = cameraParams.getSupportedPreviewSizes();

mPictureSizeList = cameraParams.getSupportedPictureSizes();

}

SurfaceHolder callbacks

public class CamPreview extends SurfaceView implements SurfaceHolder.Callback

Implement Methods

@Override

public void surfaceCreated(SurfaceHolder holder) {

//set preview holder and inti baisc params

}

@Override

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

 

//handle surface changed

}

@Override

public void surfaceDestroyed(SurfaceHolder holder) {

//Release Camera

}

Camera Utils

  • Turn On/Off Flash

Check camera available or not.

public boolean isCameraFlashAvailable() {

Camera.Parameters p = mCamera.getParameters();

return p.getFlashMode() == null ? false : true;

}

If it is available then toggle.

public void toggleFlash(boolean isEnabled) {

if (!isCameraFlashAvailable())

return;

String mode;

if (isEnabled)

mode = Camera.Parameters.FLASH_MODE_ON;

else

mode = Camera.Parameters.FLASH_MODE_OFF;

Camera.Parameters params = mCamera.getParameters();

params.setFlashMode(mode);

try {

mCamera.setParameters(params);

} catch (Exception e) {

// bypass

}

}
  • Focus

Check Focus.

public boolean hasAutofocus() {

Camera.Parameters params = mCamera.getParameters();

List<String> focusList = params.getSupportedFocusModes();

return focusList.contains(Camera.Parameters.FOCUS_MODE_AUTO);

}

Zoom

Implement GestureDetector to track touch.

public class CamPreview extends SurfaceView  GestureDetector.OnGestureListener

Check Touch and Set zoom accordingly.

@Override

public boolean onTouchEvent(MotionEvent event) {

// Get the pointer ID

Camera.Parameters params = mCamera.getParameters();

if (params == null)

return false;

int action = event.getAction();

if (event.getPointerCount() > 1) {

// handle multi-touch events

if (action == MotionEvent.ACTION_POINTER_DOWN) {

Log.v("Camera","action == MotionEvent.ACTION_POINTER_DOWN");

mDist = getFingerSpacing(event);

} else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {

mCamera.cancelAutoFocus();

handleZoom(event, params);

Log.v("Camera", "action == MotionEvent.ACTION_MOVE && params.isZoomSupported()");

}

 

} else {

// handle single touch events

if (action == MotionEvent.ACTION_UP) {

mCamera.cancelAutoFocus();

handleFocus(event, params);

Log.v("Camera","action == MotionEvent.ACTION_UP");

}

}

return true;

}

Capture Picture

public void takeShot(final Camera.PictureCallback callback) {

final Camera.Parameters p = mCamera.getParameters();

if (hasAutofocus()) {

mCamera.autoFocus(new Camera.AutoFocusCallback() {

@Override

public void onAutoFocus(boolean success, Camera camera) {

Log.v(" takeShot", "onAutoFocus");

try {

camera.takePicture(null, null, callback);

p.setRotation(180);

// camera.setParameters(p);

} catch (RuntimeException e) {

// bypass

CamActivity.isClicked = false;

e.printStackTrace();

}

}

});

} else {

try {

// mCamera.setParameters(p);

mCamera.takePicture(null, null, callback);

p.setRotation(180);

} catch (RuntimeException e) {

// bypass

e.printStackTrace();

}

}

}

Square Image

public static Bitmap cropBitmapToSquare(Bitmap bmp) {

System.gc();

Bitmap result = null;

int height = bmp.getHeight();

int width = bmp.getWidth();

if (height <= width) {

result = Bitmap.createBitmap(bmp, (width - height) / 2, 0, height,

height);

} else {

result = Bitmap.createBitmap(bmp, 0, (height - width) / 2, width,

width);

}

return result;

}

Start Code Integration

BmpUtils.java

public class BmpUtils {

// RESAMPLING functions return bitmap sized to nearest power of 2

// if you need exact size, please use RESIZING functions

 

public static Bitmap getResampledBitmap(byte[] data, int reqSize) {

return getResampledBitmap(data, reqSize, reqSize);

}

public static Bitmap getResampledBitmap(String pathName, int reqSize) {

return getResampledBitmap(pathName, reqSize, reqSize);

}

 

public static Bitmap getResampledBitmap(ContentResolver contentResolver,

Uri uri, int reqSize) {

return getResampledBitmap(contentResolver, uri, reqSize, reqSize);

}

 

public static Bitmap getResampledBitmap(byte[] data,

int reqWidth, int reqHeight) {

// First decode with inJustDecodeBounds=true to check dimensions

final BitmapFactory.Options options = new BitmapFactory.Options();

options.inJustDecodeBounds = true;

BitmapFactory.decodeByteArray(data, 0, data.length, options);

// Calculate inSampleSize

options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set

options.inJustDecodeBounds = false;

return BitmapFactory.decodeByteArray(data, 0, data.length, options);

}

public static Bitmap getResampledBitmap(String pathName,

int reqWidth, int reqHeight) {

// First decode with inJustDecodeBounds=true to check dimensions

final BitmapFactory.Options options = new BitmapFactory.Options();

options.inJustDecodeBounds = true;

BitmapFactory.decodeFile(pathName, options);

// Calculate inSampleSize

options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set

options.inJustDecodeBounds = false;

return BitmapFactory.decodeFile(pathName, options);

}

public static Bitmap getResampledBitmap(ContentResolver contentResolver,

Uri uri, int reqWidth, int reqHeight) {

// First decode with inJustDecodeBounds=true to check dimensions

final BitmapFactory.Options options = new BitmapFactory.Options();

options.inJustDecodeBounds = true;

InputStream stream = null;

try {

stream = contentResolver.openInputStream(uri);

BitmapFactory.decodeStream(stream, null, options);

} catch (FileNotFoundException e) {

return null;

} finally {

try {

if(stream != null)

stream.close();

} catch (IOException e) {

}

}

// Calculate inSampleSize

options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

// Decode bitmap with inSampleSize set

options.inJustDecodeBounds = false;

stream = null;

try {

stream = contentResolver.openInputStream(uri);

return BitmapFactory.decodeStream(stream, null, options);

} catch (FileNotFoundException e) {

return null;

} finally {

try {

if(stream != null)

stream.close();

} catch (IOException e) {

}

}

}

 

// This function is not working! Since stream cannot be rewinded.

// Consider to use other variants

@SuppressWarnings("unused")

private static Bitmap getResampledBitmap(InputStream stream,

int reqWidth, int reqHeight) {

throw new RuntimeException("sorry");

}

 

public static int calculateInSampleSize(

BitmapFactory.Options options, int reqWidth, int reqHeight) {

// Raw height and width of image

final int height = options.outHeight;

final int width = options.outWidth;

int inSampleSize = 1;

 

if (height > reqHeight || width > reqWidth) {

 

// Calculate ratios of height and width to requested height and width

final int heightRatio = Math.round((float) height / (float) reqHeight);

final int widthRatio = Math.round((float) width / (float) reqWidth);

 

// Choose the smallest ratio as inSampleSize value, this will guarantee

// a final image with both dimensions larger than or equal to the

// requested height and width.

inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;

}

 

return inSampleSize;

}

/* Use resampling function before #getResizedBitmap */

public static Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

int width = bm.getWidth();

int height = bm.getHeight();

float scaleWidth = ((float) newWidth) / width;

float scaleHeight = ((float) newHeight) / height;

// CREATE A MATRIX FOR THE MANIPULATION

Matrix matrix = new Matrix();

// RESIZE THE BIT MAP

matrix.postScale(scaleWidth, scaleHeight);

// "RECREATE" THE NEW BITMAP

System.gc();

Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,

matrix, false);

return resizedBitmap;

}

 

public static Bitmap getResizedBitmap(Bitmap bm, int newSize) {

int width = bm.getWidth();

int height = bm.getHeight();

int newWidth, newHeight;

if (width >= height) {

newHeight = newSize;

newWidth = (int) (width * ((float)newSize / height));

} else {

newWidth = newSize;

newHeight = (int) (height * ((float) newSize / width));

}

float scaleWidth = ((float) newWidth) / width;

float scaleHeight = ((float) newHeight) / height;

// CREATE A MATRIX FOR THE MANIPULATION

Matrix matrix = new Matrix();

// RESIZE THE BIT MAP

matrix.postScale(scaleWidth, scaleHeight);

// "RECREATE" THE NEW BITMAP

System.gc();

Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,

matrix, false);

return resizedBitmap;

}

 

public static Bitmap getResizedBitmap(byte[] data, int reqSize) {

return getResizedBitmap(

getResampledBitmap(data, reqSize),

reqSize);

}

public static Bitmap getResizedBitmap(String pathName, int reqSize) {

return getResizedBitmap(

getResampledBitmap(pathName, reqSize, reqSize),

reqSize, reqSize);

}

 

public static Bitmap getResizedBitmap(ContentResolver contentResolver,

Uri uri, int reqSize) {

return getResizedBitmap(

getResampledBitmap(contentResolver, uri, reqSize),

reqSize);

}

 

 

public static int getDrawableIdByName(String name) {

if (name == null)

return -1;

try {

Field field = R.drawable.class.getDeclaredField(name);

int id = field.getInt(field);

return id;

} catch (NoSuchFieldException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

}

return -1;

}

public static Bitmap cropBitmapToSquare(Bitmap bmp) {

System.gc();

Bitmap result = null;

int height = bmp.getHeight();

int width = bmp.getWidth();

if (height <= width) {

result = Bitmap.createBitmap(bmp, (width - height) / 2, 0, height,

height);

} else {

result = Bitmap.createBitmap(bmp, 0, (height - width) / 2, width,

width);

}

return result;

}

public static Bitmap cropBitmap(byte[] data) {

Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);

return cropBitmapToSquare(bmp);

}

public static Bitmap cropBitmap(InputStream is) {

return cropBitmapToSquare(BitmapFactory.decodeStream(is));

}

public static void rotateBitmap(String path, int degrees)

throws IOException {

System.gc();

Bitmap bmp = BitmapFactory.decodeFile(path);

Matrix matrix = new Matrix();

matrix.postRotate(degrees);

bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(),

matrix, false);

File file = new File(path);

FileOutputStream outStream = new FileOutputStream(file);

bmp.compress(Bitmap.CompressFormat.JPEG, 60, outStream);

outStream.close();

}

public static Bitmap rotateBitmap(Bitmap photo, int rotation,

int reqHeight, int reqWidth) {

Matrix matrix = new Matrix();

matrix.preRotate(rotation);

return Bitmap.createBitmap(photo, 0, 0,

reqHeight, reqWidth, matrix, true);

}

}

CaptureUtils.java

public class CaptureUtils {

// //////////////////////////////////////////////////////////////////////

// Fields

// //////////////////////////////////////////////////////////////////////

private Camera mCamera;

private int currentOrientation = 90;

int activeCamera = 0;

// //////////////////////////////////////////////////////////////////////

// Public methods

// //////////////////////////////////////////////////////////////////////

@SuppressWarnings("unused")

private CaptureUtils() {

initCamera();

}

public CaptureUtils(Camera camera) {

mCamera = camera;

 

Camera.Parameters params = mCamera.getParameters();

List<String> focusList = params.getSupportedFocusModes();

if (focusList.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {

params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);

}

mCamera.setParameters(params);

}

public void releaseCamera() {

if (mCamera != null) {

mCamera.release();

}

}

public Camera getCamera() {

return mCamera;

}

@SuppressLint("NewApi")

public void flipCamera() {

if (Build.VERSION.SDK_INT < 9)

return;

if (Camera.getNumberOfCameras() > 1) {

activeCamera = activeCamera == 0 ? 1 : 0;

initCamera();

}

}

public void toggleFlash(boolean isEnabled) {

if (!isCameraFlashAvailable())

return;

String mode;

if (isEnabled)

mode = Camera.Parameters.FLASH_MODE_ON;

else

mode = Camera.Parameters.FLASH_MODE_OFF;

Camera.Parameters params = mCamera.getParameters();

params.setFlashMode(mode);

try {

mCamera.setParameters(params);

} catch (Exception e) {

// bypass

}

}

public boolean isCameraFlashAvailable() {

Camera.Parameters p = mCamera.getParameters();

return p.getFlashMode() == null ? false : true;

}

public boolean isCameraFlashEnabled() {

Camera.Parameters p = mCamera.getParameters();

String flashMode = p.getFlashMode();

if (flashMode == null)

return false;

return flashMode.equals(Camera.Parameters.FLASH_MODE_ON);

}

public void takeShot(final Camera.PictureCallback callback) {

final Camera.Parameters p = mCamera.getParameters();

if (hasAutofocus()) {

mCamera.autoFocus(new Camera.AutoFocusCallback() {

@Override

public void onAutoFocus(boolean success, Camera camera) {

Log.v(" takeShot", "onAutoFocus");

try {

camera.takePicture(null, null, callback);

p.setRotation(180);

// camera.setParameters(p);

} catch (RuntimeException e) {

// bypass

CamActivity.isClicked = false;

e.printStackTrace();

}

}

});

} else {

try {

// mCamera.setParameters(p);

mCamera.takePicture(null, null, callback);

p.setRotation(180);

} catch (RuntimeException e) {

// bypass

e.printStackTrace();

}

}

}

public boolean hasAutofocus() {

Camera.Parameters params = mCamera.getParameters();

List<String> focusList = params.getSupportedFocusModes();

return focusList.contains(Camera.Parameters.FOCUS_MODE_AUTO);

}

public PictureSize getPreviewSize(int reqHeight) {

if (mCamera == null)

return null;

Camera.Parameters params = mCamera.getParameters();

List<Camera.Size> sizes = params.getSupportedPreviewSizes();

if (sizes.size() == 0)

return null;

Camera.Size size = sizes.get(0);

float k = (float) reqHeight / size.height;

int reqWidth = (int) (size.width * k);

PictureSize reqSize = new PictureSize();

reqSize.width = reqWidth;

reqSize.height = reqHeight;

params.setPreviewSize(reqWidth, reqHeight);

return reqSize;

}

public static class PictureSize {

public int width;

public int height;

}

// //////////////////////////////////////////////////////////////////////

// Private methods

// //////////////////////////////////////////////////////////////////////

@SuppressWarnings("deprecation")

@SuppressLint("NewApi")

private void initCamera() {

releaseCamera();

if (Build.VERSION.SDK_INT < 9)

mCamera = Camera.open();

else

mCamera = Camera.open(activeCamera);

if (mCamera != null) {

// mCamera.setDisplayOrientation(currentOrientation);

toggleFlash(true);

}

}

}

@SuppressLint("NewApi")

CamPreview.java

public class CamPreview extends SurfaceView implements SurfaceHolder.Callback, GestureDetector.OnGestureListener {

private static boolean DEBUGGING = false;

//    private static final String LOG_TAG = CamPreview.class.getSimpleName();

private static final String CAMERA_PARAM_ORIENTATION = "orientation";

private static final String CAMERA_PARAM_LANDSCAPE = "landscape";

private static final String CAMERA_PARAM_PORTRAIT = "portrait";

protected Activity mActivity;

private SurfaceHolder mHolder;

protected Camera mCamera;

protected List<Camera.Size> mPreviewSizeList;

protected List<Camera.Size> mPictureSizeList;

protected Camera.Size mPreviewSize;

protected Camera.Size mPictureSize;

private int mSurfaceChangedCallDepth = 0;

private int mCameraId;

private LayoutMode mLayoutMode;

private int mCenterPosX = -1;

private int mCenterPosY;

private float mDist = 0;

PreviewReadyCallback mPreviewReadyCallback = null;

private ZoomCallback zoomCallback = null;

public static enum LayoutMode {

FitToParent, // Scale to the size that no side is larger than the parent

NoBlank // Scale to the size that no side is smaller than the parent

}

public interface PreviewReadyCallback {

public void onPreviewReady();

}

public interface ZoomCallback {

public void onZoomChanged(int progress);

}

/**

* State flag: true when surface's layout size is set and surfaceChanged()

* process has not been completed.

*/

protected boolean mSurfaceConfiguring = false;

public CamPreview(Activity activity, int cameraId, LayoutMode mode) {

super(activity); // Always necessary

mActivity = activity;

mLayoutMode = mode;

mHolder = getHolder();

mHolder.addCallback(this);

mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {

if (Camera.getNumberOfCameras() > cameraId) {

mCameraId = cameraId;

} else {

mCameraId = 0;

}

} else {

mCameraId = 0;

}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {

mCamera = Camera.open(mCameraId);

} else {

mCamera = Camera.open();

}

Camera.Parameters cameraParams = mCamera.getParameters();

mPreviewSizeList = cameraParams.getSupportedPreviewSizes();

mPictureSizeList = cameraParams.getSupportedPictureSizes();

}

@Override

public boolean onTouchEvent(MotionEvent event) {

// Get the pointer ID

Camera.Parameters params = mCamera.getParameters();

if (params == null)

return false;

int action = event.getAction();

if (event.getPointerCount() > 1) {

// handle multi-touch events

if (action == MotionEvent.ACTION_POINTER_DOWN) {

Log.v("Camera","action == MotionEvent.ACTION_POINTER_DOWN");

mDist = getFingerSpacing(event);

} else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {

mCamera.cancelAutoFocus();

handleZoom(event, params);

Log.v("Camera", "action == MotionEvent.ACTION_MOVE && params.isZoomSupported()");

}

} else {

// handle single touch events

if (action == MotionEvent.ACTION_UP) {

mCamera.cancelAutoFocus();

handleFocus(event, params);

Log.v("Camera","action == MotionEvent.ACTION_UP");

}

}

return true;

}

private void handleZoom(MotionEvent event, Camera.Parameters params) {

int maxZoom = params.getMaxZoom();

int zoom = params.getZoom();

float newDist = getFingerSpacing(event);

if (newDist > mDist) {

//zoom in

if (zoom < maxZoom)

zoom++;

} else if (newDist < mDist) {

//zoom out

if (zoom > 0)

zoom--;

}

mDist = newDist;

params.setZoom(zoom);

mCamera.setParameters(params);

if (zoomCallback != null) {

zoomCallback.onZoomChanged((zoom * 100 / maxZoom));

}

Log.e("Zoom", "MAX :" + maxZoom + "Zoom %" + (zoom * 100 / maxZoom));

}

public void handleFocus(MotionEvent event, Camera.Parameters params) {

int pointerId = event.getPointerId(0);

int pointerIndex = event.findPointerIndex(pointerId);

// Get the pointer's current position

float x = event.getX(pointerIndex);

float y = event.getY(pointerIndex);

List<String> supportedFocusModes = params.getSupportedFocusModes();

if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {

try {

mCamera.autoFocus(new Camera.AutoFocusCallback() {

@Override

public void onAutoFocus(boolean b, Camera camera) {

// currently set to auto-focus on single touch

}

});

} catch (RuntimeException e) {

e.printStackTrace();

}

}

}

/**

* Determine the space between the first two fingers

*/

private float getFingerSpacing(MotionEvent event) {

// ...

double x = event.getX(0) - event.getX(1);

double y = event.getY(0) - event.getY(1);

return (float) Math.sqrt(x * x + y * y);

}

@Override

public void surfaceCreated(SurfaceHolder holder) {

try {

mCamera.setPreviewDisplay(mHolder);

Log.v("Camera","surfaceCreated");

} catch (IOException e) {

mCamera.release();

mCamera = null;

}

}

@Override

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

mSurfaceChangedCallDepth++;

doSurfaceChanged(width, height);

mSurfaceChangedCallDepth--;

}

private void doSurfaceChanged(int width, int height) {

mCamera.stopPreview();

Camera.Parameters cameraParams = mCamera.getParameters();

boolean portrait = isPortrait();

// The code in this if-statement is prevented from executed again when

// surfaceChanged is

// called again due to the change of the layout size in this

// if-statement.

if (!mSurfaceConfiguring) {

Camera.Size previewSize = determinePreviewSize(portrait, width, height);

Camera.Size pictureSize = determinePictureSize(previewSize);

mPreviewSize = previewSize;

mPictureSize = pictureSize;

mSurfaceConfiguring = adjustSurfaceLayoutSize(previewSize, portrait, width, height);

// Continue executing this method if this method is called

// recursively.

// Recursive call of surfaceChanged is very special case, which is a

// path from

// the catch clause at the end of this method.

// The later part of this method should be executed as well in the

// recursive

// invocation of this method, because the layout change made in this

// recursive

// call will not trigger another invocation of this method.

if (mSurfaceConfiguring && (mSurfaceChangedCallDepth <= 1)) {

return;

}

}

configureCameraParameters(cameraParams, portrait);

mSurfaceConfiguring = false;

try {

mCamera.startPreview();

} catch (Exception e) {

// Remove failed size

mPreviewSizeList.remove(mPreviewSize);

mPreviewSize = null;

// Reconfigure

if (mPreviewSizeList.size() > 0) { // prevent infinite loop

surfaceChanged(null, 0, width, height);

} else {

Toast.makeText(mActivity, "Can't start preview", Toast.LENGTH_LONG).show();

}

}

if (null != mPreviewReadyCallback) {

mPreviewReadyCallback.onPreviewReady();

}

}

/**

* @param portrait

* @param reqWidth  must be the value of the parameter passed in surfaceChanged

* @param reqHeight must be the value of the parameter passed in surfaceChanged

* @return Camera.Size object that is an element of the list returned from

* Camera.Parameters.getSupportedPreviewSizes.

*/

protected Camera.Size determinePreviewSize(boolean portrait, int reqWidth, int reqHeight) {

// Meaning of width and height is switched for preview when portrait,

// while it is the same as user's view for surface and metrics.

// That is, width must always be larger than height for setPreviewSize.

int reqPreviewWidth; // requested width in terms of camera hardware

int reqPreviewHeight; // requested height in terms of camera hardware

if (portrait) {

reqPreviewWidth = reqHeight;

reqPreviewHeight = reqWidth;

} else {

reqPreviewWidth = reqWidth;

reqPreviewHeight = reqHeight;

}

/*

* // Adjust surface size with the closest aspect-ratio float reqRatio =

* ((float) reqPreviewWidth) / reqPreviewHeight; float curRatio,

* deltaRatio; float deltaRatioMin = Float.MAX_VALUE; Camera.Size

* retSize = null; for (Camera.Size size : mPreviewSizeList) { curRatio

* = ((float) size.width) / size.height; deltaRatio = Math.abs(reqRatio

* - curRatio); if (deltaRatio < deltaRatioMin) { deltaRatioMin =

* deltaRatio; retSize = size; } }

*/

Display display = mActivity.getWindowManager().getDefaultDisplay();

DisplayMetrics outMetrics = new DisplayMetrics();

display.getMetrics(outMetrics);

Camera.Size retSize = null;

int scrWidth = reqPreviewWidth;

int found = scrWidth;

for (Camera.Size size : mPreviewSizeList) {

int diff = Math.abs(scrWidth - size.width);

if (diff < found) {

found = diff;

retSize = size;

}

}

if (retSize == null) {

if (mPreviewSizeList != null && mPreviewSizeList.size() > 0) {

retSize =mPreviewSizeList.get(0);

}

}

return retSize;

}

protected Camera.Size determinePictureSize(Camera.Size previewSize) {

Camera.Size retSize = null;

for (Camera.Size size : mPictureSizeList) {

if (size.equals(previewSize)) {

return size;

}

}

// if the preview size is not supported as a picture size

float reqRatio = ((float) previewSize.width) / previewSize.height;

float curRatio, deltaRatio;

float deltaRatioMin = Float.MAX_VALUE;

for (Camera.Size size : mPictureSizeList) {

curRatio = ((float) size.width) / size.height;

deltaRatio = Math.abs(reqRatio - curRatio);

if (deltaRatio < deltaRatioMin) {

deltaRatioMin = deltaRatio;

retSize = size;

}

}

return retSize;

}

protected boolean adjustSurfaceLayoutSize(Camera.Size previewSize, boolean portrait,

int availableWidth, int availableHeight) {

float tmpLayoutHeight, tmpLayoutWidth;

if (portrait) {

tmpLayoutHeight = previewSize.width;

tmpLayoutWidth = previewSize.height;

} else {

tmpLayoutHeight = previewSize.height;

tmpLayoutWidth = previewSize.width;

}

float factH, factW, fact;

factH = availableHeight / tmpLayoutHeight;

factW = availableWidth / tmpLayoutWidth;

if (mLayoutMode == LayoutMode.FitToParent) {

// Select smaller factor, because the surface cannot be set to the

// size larger than display metrics.

if (factH < factW) {

fact = factH;

} else {

fact = factW;

}

} else {

if (factH < factW) {

fact = factW;

} else {

fact = factH;

}

}

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this.getLayoutParams();

int layoutHeight = (int) (tmpLayoutHeight * fact);

int layoutWidth = (int) (tmpLayoutWidth * fact);

boolean layoutChanged;

if ((layoutWidth != this.getWidth()) || (layoutHeight != this.getHeight())) {

layoutParams.height = layoutHeight;

layoutParams.width = layoutWidth;

if (mCenterPosX >= 0) {

layoutParams.topMargin = mCenterPosY - (layoutHeight / 2);

layoutParams.leftMargin = mCenterPosX - (layoutWidth / 2);

}

this.setLayoutParams(layoutParams); // this will trigger another

// surfaceChanged invocation.

layoutChanged = true;

} else {

layoutChanged = false;

}

return layoutChanged;

}

/**

* @param x X coordinate of center position on the screen. Set to negative

*          value to unset.

* @param y Y coordinate of center position on the screen.

*/

public void setCenterPosition(int x, int y) {

mCenterPosX = x;

mCenterPosY = y;

}

protected void configureCameraParameters(Camera.Parameters cameraParams, boolean portrait) {

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) { // for 2.1 and

// before

if (portrait) {

cameraParams.set(CAMERA_PARAM_ORIENTATION, CAMERA_PARAM_PORTRAIT);

} else {

cameraParams.set(CAMERA_PARAM_ORIENTATION, CAMERA_PARAM_LANDSCAPE);

}

} else { // for 2.2 and later

int angle;

Display display = mActivity.getWindowManager().getDefaultDisplay();

switch (display.getRotation()) {

case Surface.ROTATION_0: // This is display orientation

angle = 90; // This is camera orientation

break;

case Surface.ROTATION_90:

angle = 270;

break;

case Surface.ROTATION_180:

angle = 270;

break;

case Surface.ROTATION_270:

angle = 90;

break;

default:

angle = 90;

break;

}

mCamera.setDisplayOrientation(angle);

}

cameraParams.setPreviewSize(mPreviewSize.width, mPreviewSize.height);

cameraParams.setPictureSize(mPictureSize.width, mPictureSize.height);

mCamera.setParameters(cameraParams);

}

@Override

public void surfaceDestroyed(SurfaceHolder holder) {

stop();

}

public void stop() {

if (null == mCamera) {

return;

}

mCamera.stopPreview();

mCamera.release();

mCamera = null;

}

public boolean isPortrait() {

return (mActivity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);

}

public void setOneShotPreviewCallback(Camera.PreviewCallback callback) {

if (null == mCamera) {

return;

}

mCamera.setOneShotPreviewCallback(callback);

}

public void setPreviewCallback(Camera.PreviewCallback callback) {

if (null == mCamera) {

return;

}

mCamera.setPreviewCallback(callback);

}

public Camera.Size getPreviewSize() {

return mPreviewSize;

}

public void setOnPreviewReady(PreviewReadyCallback cb) {

mPreviewReadyCallback = cb;

}

public void setOnZoomCallback(ZoomCallback zoomCallback) {

this.zoomCallback = zoomCallback;

}

public Camera getCamera() {

return mCamera;

}

@Override

public boolean onDown(MotionEvent e) {

return true;

}

@Override

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

return false;

}

@Override

public void onLongPress(MotionEvent e) {

}

@Override

public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

return false;

}

@Override

public void onShowPress(MotionEvent e) {

}

@Override

public boolean onSingleTapUp(MotionEvent e) {

 

return false;

}

public void onProgressChanged(int progress) {

Camera camera = getCamera();

if (camera != null && camera.getParameters() != null) {

camera.cancelAutoFocus();

Camera.Parameters params = mCamera.getParameters();

int maxZoom = params.getMaxZoom();

int zoom = (int) (maxZoom * ((float) progress / 100));

params.setZoom(zoom);

mCamera.setParameters(params);

}

}

public void onStopTrackingTouch(int progress) {

Camera camera = getCamera();

if (camera != null && camera.getParameters() != null) {

Camera.Parameters params = mCamera.getParameters();

camera.cancelAutoFocus();

//Check For AutoFocus

List<String> supportedFocusModes = params.getSupportedFocusModes();

if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {

camera.autoFocus(new Camera.AutoFocusCallback() {

@Override

public void onAutoFocus(boolean b, Camera camera) {

// currently set to auto-focus on single touch

}

});

}

}

}

}

CamActivity.java

public class CamActivity extends Activity {

private final int RC_GET_PICTURE = 301;

private CamPreview mPreview;

private RelativeLayout previewParent;

private LinearLayout blackTop;

private LinearLayout blackBottom;

private ImageButton ibFlash;

private ImageButton ibGrid;

private ImageView ivGridLines;

private LinearLayout llGallery;

private TextView textCamera;

private SeekBar sbZoom;

private CaptureUtils captureUtils;

private boolean flashEnabled = false;

private int activeCamera = 0;

private OrientationEventListener orientationListener;

private int screenOrientation = 90;

private int THRESHOLD = 30;

public static boolean isClicked = false;

private ImageButton ibFlipCamera;

@SuppressLint("NewApi")

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Hide status-bar

getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

// Hide title-bar, must be before setContentView

requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.activity_cam);

InitControls();

}

@TargetApi(Build.VERSION_CODES.GINGERBREAD)

void InitControls() {

previewParent = (RelativeLayout) findViewById(R.id.rlPreview);

blackTop = (LinearLayout) findViewById(R.id.llBlackTop);

blackBottom = (LinearLayout) findViewById(R.id.llBlackBottom);

llGallery = (LinearLayout) findViewById(R.id.llGallery);

ibFlash = (ImageButton) findViewById(R.id.ibFlash);

ibGrid = (ImageButton) findViewById(R.id.ibGrid);

ivGridLines = (ImageView) findViewById(R.id.ivGridLines);

ibFlipCamera = (ImageButton) findViewById(R.id.ibFlipCamera);

sbZoom = (SeekBar) findViewById(R.id.sbZoom);

if (Camera.getNumberOfCameras() > 1) {

ibFlipCamera.setVisibility(View.VISIBLE);

} else {

ibFlipCamera.setVisibility(View.GONE);

}

orientationListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) {

public void onOrientationChanged(int orientation) {

if (isOrientation(orientation, 0))

screenOrientation = 0;

else if (isOrientation(orientation, 90))

screenOrientation = 90;

else if (isOrientation(orientation, 180))

screenOrientation = 180;

else if (isOrientation(orientation, 270))

screenOrientation = 270;

}

};

}

protected boolean isOrientation(int orientation, int degree) {

return (degree - THRESHOLD <= orientation && orientation <= degree + THRESHOLD);

}

@Override

protected void onResume() {

super.onResume();

isClicked = false;

//        checkLocationEnabled();

int currentapiVersion = android.os.Build.VERSION.SDK_INT;

orientationListener.enable();

setupCamera(activeCamera);

if (sbZoom.getVisibility() == View.VISIBLE) {

sbZoom.setProgress(0);

}

showLatestPhoto();

}

@Override

protected void onPause() {

super.onPause();

releaseCamera();

orientationListener.disable();

}

private void setupCamera(final int camera) {

// Set the second argument by your choice.

// Usually, 0 for back-facing camera, 1 for front-facing camera.

// If the OS is pre-gingerbreak, this does not have any effect.

try {

mPreview = new CamPreview(this, camera, CamPreview.LayoutMode.NoBlank);// .FitToParent);

} catch (Exception e) {

Toast.makeText(this, R.string.cannot_connect_to_camera, Toast.LENGTH_LONG).show();

finish();

return;

}

LayoutParams previewLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

// Un-comment below lines to specify the size.

Display display = getWindowManager().getDefaultDisplay();

DisplayMetrics outMetrics = new DisplayMetrics();

display.getMetrics(outMetrics);

int width = outMetrics.widthPixels;

int height = outMetrics.heightPixels;

previewLayoutParams.height = width;

previewLayoutParams.width = width;

// Un-comment below line to specify the position.

mPreview.setCenterPosition(width / 2, height / 2);

previewParent.addView(mPreview, 0, previewLayoutParams);

// there is changes in calculations

// camera preview image centered now to have actual image at center of

// view

int delta = height - width;

int btHeight = 0;// blackTop.getHeight();

int fix = delta - btHeight;

int fix2 = 0;// fix / 4;

FrameLayout.LayoutParams blackBottomParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, fix / 2 + fix2);

blackBottomParams.gravity = Gravity.BOTTOM;

blackBottom.setLayoutParams(blackBottomParams);

FrameLayout.LayoutParams blackTopParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, fix / 2 - fix2);

blackTopParams.gravity = Gravity.TOP;

blackTop.setLayoutParams(blackTopParams);

captureUtils = new CaptureUtils(mPreview.getCamera());

if (captureUtils.isCameraFlashAvailable()) {

captureUtils.toggleFlash(flashEnabled);

ibFlash.setVisibility(View.VISIBLE);

ibFlash.setImageResource(flashEnabled ? R.drawable.flash : R.drawable.flash_off);

} else {

ibFlash.setVisibility(View.GONE);

}

mPreview.setOnZoomCallback(new CamPreview.ZoomCallback() {

@Override

public void onZoomChanged(int progress) {

sbZoom.setProgress(progress);

}

});

sbZoom.setVisibility(captureUtils.hasAutofocus() ? View.VISIBLE : View.GONE);

sbZoom.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

@Override

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

if (mPreview != null) {

mPreview.onProgressChanged(progress);

}

}

@Override

public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override

public void onStopTrackingTouch(SeekBar seekBar) {

if (mPreview != null && seekBar != null) {

mPreview.onStopTrackingTouch(seekBar.getProgress());

}

}

});

}

private void releaseCamera() {

if (mPreview != null) {

mPreview.stop();

previewParent.removeView(mPreview); // This is necessary.

mPreview = null;

}

}

@SuppressLint("NewApi")

public void flipClick(View view) {

if (Build.VERSION.SDK_INT < 9)

return;

if (Camera.getNumberOfCameras() > 1) {

activeCamera = activeCamera == 0 ? 1 : 0;

releaseCamera();

setupCamera(activeCamera);

}

}

public void flashClick(View view) {

if (!captureUtils.isCameraFlashAvailable())

return;

flashEnabled = !flashEnabled;

captureUtils.toggleFlash(flashEnabled);

ibFlash.setImageResource(flashEnabled ? R.drawable.flash : R.drawable.flash_off);

}

public void captureClick(View view) {

try {

if (!isClicked) {

captureUtils.takeShot(jpegCallback);

isClicked = true;

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public void selectFromGallery(View view) {

Intent iGetAvatar = new Intent(Intent.ACTION_PICK, Images.Media.EXTERNAL_CONTENT_URI);

startActivityForResult(iGetAvatar, RC_GET_PICTURE);

}

PictureCallback jpegCallback = new PictureCallback() {

public void onPictureTaken(byte[] data, Camera camera) {

FileOutputStream outStream = null;

try {

System.gc();

Bitmap bmp = BmpUtils.getResampledBitmap(data, 800);

bmp = BmpUtils.cropBitmapToSquare(bmp);

// Write to file

//                File file = File.createTempFile("cam", "tmp", getFilesDir());

// File file = new

// File(Environment.getExternalStorageDirectory(), "cam.jpg");

//                outStream = new FileOutputStream(file);

String FILENAME = "tmp" + System.currentTimeMillis() + ".jpg";

outStream = openFileOutput(FILENAME, Context.MODE_PRIVATE);

bmp.compress(Bitmap.CompressFormat.JPEG, 60, outStream);

// outStream.write(data);

outStream.close();

resetCam();

String path = getFilesDir() + "/" + FILENAME;

int orientation = 0;

int fix = 1;

if (activeCamera == 0) {

ExifInterface ei = new ExifInterface(path);

orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

ei.setAttribute(ExifInterface.TAG_ORIENTATION, "90");

ei.saveAttributes();

} else {

ExifInterface ei = new ExifInterface(path);

orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

ei.setAttribute(ExifInterface.TAG_ORIENTATION, "0");

ei.saveAttributes();

orientation = ExifInterface.ORIENTATION_ROTATE_270;

fix = -1;

}

switch (orientation) {

case ExifInterface.ORIENTATION_UNDEFINED:

BmpUtils.rotateBitmap(path, normalizeRot(90 + screenOrientation));

break;

case ExifInterface.ORIENTATION_ROTATE_90:

BmpUtils.rotateBitmap(path, normalizeRot(90 + screenOrientation));

break;

case ExifInterface.ORIENTATION_ROTATE_180:

BmpUtils.rotateBitmap(path, normalizeRot(180 + screenOrientation));

break;

case ExifInterface.ORIENTATION_ROTATE_270:

BmpUtils.rotateBitmap(path, normalizeRot(270 + fix * screenOrientation));

break;

case ExifInterface.ORIENTATION_NORMAL:

BmpUtils.rotateBitmap(path, normalizeRot(screenOrientation));

break;

}

selectCategory(path);

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

}

}

};

protected void selectCategory(String path) {

Intent iSelect = new Intent(this, ShowPhotoActivity.class);

iSelect.putExtra("path", path);

startActivity(iSelect);

}

protected void resetCam() {

Camera camera = mPreview.getCamera();

camera.startPreview();

showLatestPhoto();

}

protected int normalizeRot(int rot) {

if (rot < 0)

rot += 360;

if (rot > 360)

rot -= 360;

return rot;

}

/**

* Returns how much we have to rotate

*/

public int rotationForImage(Uri uri) {

try {

if (uri.getScheme().equals("content")) {

// From the media gallery

String[] projection = {Images.ImageColumns.ORIENTATION};

Cursor c = getContentResolver().query(uri, projection, null, null, null);

if (c.moveToFirst()) {

return c.getInt(0);

}

} else if (uri.getScheme().equals("file")) {

// From a file saved by the camera

ExifInterface exif = new ExifInterface(uri.getPath());

int rotation = (int) exifOrientationToDegrees(exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL));

return rotation;

}

return 0;

} catch (IOException e) {

e.printStackTrace();

return 0;

}

}

/**

* Get rotation in degrees

*/

private static int exifOrientationToDegrees(int exifOrientation) {

if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {

return 90;

} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {

return 180;

} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {

return 270;

}

return 0;

}

private void showLatestPhoto() {

String[] projection = new String[]{Images.ImageColumns._ID, Images.ImageColumns.DATA,

Images.ImageColumns.BUCKET_DISPLAY_NAME, Images.ImageColumns.DATE_TAKEN, Images.ImageColumns.MIME_TYPE};

@SuppressWarnings("deprecation")

final Cursor cursorE = managedQuery(Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, Images.ImageColumns.DATE_TAKEN

+ " DESC");

@SuppressWarnings("deprecation")

final Cursor cursorI = managedQuery(Images.Media.INTERNAL_CONTENT_URI, projection, null, null, Images.ImageColumns.DATE_TAKEN

+ " DESC");

String imageLocation = null;

long udate = 0;

if (cursorE.moveToFirst()) {

udate = cursorE.getLong(3);

imageLocation = cursorE.getString(1);

}

if (cursorI.moveToFirst()) {

long iudate = cursorI.getLong(3);

if (iudate > udate)

imageLocation = cursorI.getString(1);

}

if (imageLocation == null)

return;

final ImageView imageView = (ImageView) findViewById(R.id.ivGallery);

int rot = rotationForImage(Uri.parse("file://" + imageLocation));

File imageFile = new File(imageLocation);

if (imageFile.exists()) {

Bitmap bm = BmpUtils.getResampledBitmap(imageLocation, 100);

if (rot != 0)

bm = BmpUtils.rotateBitmap(bm, rot, 100, 100);

imageView.setImageBitmap(bm);

}

}

public void gridClick(View v) {

boolean visible = ivGridLines.isShown();

ivGridLines.setVisibility(visible ? View.GONE : View.VISIBLE);

}

}

Activity_cam.xml

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout

android:id="@+id/layout"

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:background="@color/black"

xmlns:app="http://schemas.android.com/apk/res-auto">

<RelativeLayout

android:id="@+id/rlPreview"

android:layout_width="match_parent"

android:layout_height="match_parent">

</RelativeLayout>

<LinearLayout

android:id="@+id/llBlackTop"

android:layout_width="match_parent"

android:layout_height="60dp"

android:background="@color/black"

android:orientation="vertical">

</LinearLayout>

<LinearLayout

android:id="@+id/llBlackBottom"

android:layout_width="match_parent"

android:layout_height="120dp"

android:layout_gravity="bottom"

android:background="@color/black"

android:orientation="vertical">

</LinearLayout>

<ImageView

android:id="@+id/ivGridLines"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_gravity="center_vertical|center_horizontal"

android:adjustViewBounds="true"

android:scaleType="centerInside"

android:src="@drawable/gridlines"

android:visibility="gone"/>

<FrameLayout

android:id="@+id/flTitle"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:paddingLeft="10dp"

android:paddingRight="10dp">

<TextView

android:id="@+id/tfCancel"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="left|center_vertical"

android:clickable="true"

android:onClick="cancelClick"

android:padding="5dp"

android:visibility="gone"

android:textColor="@color/white"/>

<LinearLayout

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:layout_gravity="right|center_vertical"

android:gravity="center_vertical">

<ImageButton

android:id="@+id/ibFlipCamera"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="@color/transparent"

android:onClick="flipClick"

android:padding="4dp"

android:src="@drawable/camera_flip"/>

<ImageButton

android:id="@+id/ibGrid"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="@color/transparent"

android:onClick="gridClick"

android:paddingBottom="4dp"

android:paddingLeft="10dp"

android:paddingRight="10dp"

android:paddingTop="4dp"

android:src="@drawable/grid"/>

<ImageButton

android:id="@+id/ibFlash"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:background="@color/transparent"

android:onClick="flashClick"

android:paddingBottom="4dp"

android:paddingLeft="10dp"

android:paddingRight="10dp"

android:paddingTop="4dp"

android:src="@drawable/flash"/>

</LinearLayout>

</FrameLayout>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

android:layout_gravity="bottom"

>

<SeekBar

android:id="@+id/sbZoom"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:visibility="visible"/>

<FrameLayout

android:id="@+id/flControl"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="@color/black"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="7dp">

<LinearLayout

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center"

android:orientation="vertical">

<ImageButton

android:id="@+id/imageButton1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginBottom="2dp"

android:layout_marginTop="2dp"

android:background="@color/transparent"

android:onClick="captureClick"

android:src="@drawable/capture_button"/>

<TextView

android:id="@+id/textCamera"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="bottom|center_horizontal"

android:layout_marginBottom="2dp"

android:layout_marginTop="2dp"

android:text="Capture Pic"

android:textAppearance="?android:attr/textAppearanceSmallInverse"

android:textColor="@color/white"/>

</LinearLayout>

<LinearLayout

android:id="@+id/llGallery"

android:layout_width="wrap_content"

android:layout_height="match_parent"

android:layout_gravity="left|center_vertical"

android:gravity="center_horizontal"

android:orientation="vertical"

android:visibility="visible">

<ImageView

android:visibility="gone"

android:id="@+id/ivGallery"

android:layout_width="60dp"

android:layout_height="60dp"

android:clickable="false"

android:onClick="selectFromGallery"

android:scaleType="centerCrop" />

<TextView

android:id="@+id/typefaceTextView1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginTop="2dp"

android:textColor="@color/white"/>

</LinearLayout>

</FrameLayout>

</LinearLayout>

</FrameLayout>

ShowPhotoActivity.java

public class ShowPhotoActivity extends Activity {

private String imagePath;

private ImageView ivImage;

private boolean fromEdit = false;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_show_photo);

Bundle extras = getIntent().getExtras();

if (extras != null) {

if (extras.containsKey("path")) {

imagePath = extras.getString("path");

}

}

InitControls();

}

void InitControls() {

ivImage = (ImageView) findViewById(R.id.ivImage);

ivImage.setImageURI(Uri.parse(imagePath));

}

}

Activity_show_photo.java

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:gesture-image="http://schemas.polites.com/android"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:background="@android:color/white"

android:orientation="vertical">

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical">

<FrameLayout

android:id="@+id/container"

android:layout_width="fill_parent"

android:layout_height="0dp"

android:layout_marginBottom="10dp"

android:layout_weight="1">

<ImageView

android:id="@+id/ivImage"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:layout_gravity="center" />

</FrameLayout>

</LinearLayout>

</FrameLayout>

We are done!

However, if you face any issue, you can contact our iPhone developers for help.

As mentioned earlier that integration of Android Camera API is done in two ways. But we strongly recommend and follow the second way (custom way). The reason is, it provides complete freedom to explore the Android Camera API features and implement those features the way we want.

Additionally, it also helps to build more interactive interface of the Android app. And we always recommend it to our clients as well. Nevertheless, point is, if you’re building your own Android app that includes camera features, even a simple one, always prefer to do it the custom way. And if you need assistance, you can hire Android app developer from us to do the job for you, the right way!

Grab a free copy of Android Camera API demo from Github.

This page was last edited on May 3rd, 2018, at 3:39.
 
0
Shares
 

Want to Develop Feature-rich Android App? Contact Us Now

Get your free consultation now