Custom Camera Android

Custom camera android

Use this code

PreviewDemo.java

public class PreviewDemo extends Activity implements OnClickListener {

private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
ImageView image;
Bitmap bmp, itembmp;
static Bitmap mutableBitmap;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
File imageFileName = null;
File imageFileFolder = null;
private MediaScannerConnection msConn;
Display d;
int screenhgt, screenwdh;
ProgressDialog dialog;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview);

image = (ImageView) findViewById(R.id.image);
preview = (SurfaceView) findViewById(R.id.surface);

previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

previewHolder.setFixedSize(getWindow().getWindowManager()
.getDefaultDisplay().getWidth(), getWindow().getWindowManager()
.getDefaultDisplay().getHeight());

}

@Override
public void onResume() {
super.onResume();
camera = Camera.open();
}

@Override
public void onPause() {
if (inPreview) {
camera.stopPreview();
}

camera.release();
camera = null;
inPreview = false;
super.onPause();
}

private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size: parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
}
return (result);
}

SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
Toast.makeText(PreviewDemo.this, t.getMessage(), Toast.LENGTH_LONG)
.show();
}
}

public void surfaceChanged(SurfaceHolder holder,
int format, int width,
int height) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height,
parameters);

if (size != null) {
parameters.setPreviewSize(size.width, size.height);
camera.setParameters(parameters);
camera.startPreview();
inPreview = true;
}
}

public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
};

Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(final byte[] data, final Camera camera) {
dialog = ProgressDialog.show(PreviewDemo.this, "", "Saving Photo");
new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (Exception ex) {}
onPictureTake(data, camera);
}
}.start();
}
};

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

bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
savePhoto(mutableBitmap);
dialog.dismiss();
}

class SavePhotoTask extends AsyncTask < byte[], String, String > {@Override
protected String doInBackground(byte[]...jpeg) {
File photo = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return (null);
}
}

public void savePhoto(Bitmap bmp) {
imageFileFolder = new File(Environment.getExternalStorageDirectory(), "Rotate");
imageFileFolder.mkdir();
FileOutputStream out = null;
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH)) + fromInt(c.get(Calendar.DAY_OF_MONTH)) + fromInt(c.get(Calendar.YEAR)) + fromInt(c.get(Calendar.HOUR_OF_DAY)) + fromInt(c.get(Calendar.MINUTE)) + fromInt(c.get(Calendar.SECOND));
imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
scanPhoto(imageFileName.toString());
out = null;
} catch (Exception e) {
e.printStackTrace();
}
}

public String fromInt(int val) {
return String.valueOf(val);
}

public void scanPhoto(final String imageFileName) {
msConn = new MediaScannerConnection(PreviewDemo.this, new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msConn.scanFile(imageFileName, null);
Log.i("msClient obj in Photo Utility", "connection established");
}
public void onScanCompleted(String path, Uri uri) {
msConn.disconnect();
Log.i("msClient obj in Photo Utility", "scan completed");
}
});
msConn.connect();
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
onBack();
}
return super.onKeyDown(keyCode, event);
}

public void onBack() {
Log.e("onBack :", "yes");
camera.takePicture(null, null, photoCallback);
inPreview = false;
}

@Override
public void onClick(View v) {

}

}

Preview.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<android.view.SurfaceView
android:id="@+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>

</RelativeLayout>

Use device Menu button to take picture.

Add the permissions in Manifest file

Check Rotate folder in Gallery for the captured image.

Custom Camera Preview Android

It won't show your activity, because the intent you specify is ACTION_IMAGE_CAPTURE which states:

Standard Intent action that can be sent to have the camera application capture an image and return it.

If you have your custom activity to handle camera capture/preview/etc. you need to call new Intent(Context, YourActivity.class)

In custom camera is not getting clear image capture in android

Fixed the issue by adding below Code:-

Camera.Parameters params = c.getParameters();
if (params.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
} else {
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
c.setParameters(params);

Custom Square camera - Android

Try to implements SurfaceHolder.Callback and use Custom Surface view as you want like this:

public class TakePicture extends Activity implements SurfaceHolder.Callback {
// a variable to store a reference to the Image View at the main.xml file
// private ImageView iv_image;
// a variable to store a reference to the Surface View at the main.xml file
private SurfaceView sv;

// a bitmap to display the captured image
private Bitmap bmp;
FileOutputStream fo;

// Camera variables
// a surface holder
private SurfaceHolder sHolder;
// a variable to control the camera
private Camera mCamera;
// the camera parameters
private Parameters parameters;
private String FLASH_MODE ;
private boolean isFrontCamRequest = false;

/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_surface_holder);

// check if this device has a camera
if (checkCameraHardware(getApplicationContext())) {
// get the Image View at the main.xml file
// iv_image = (ImageView) findViewById(R.id.imageView);

// get the Surface View at the main.xml file
Bundle extras = getIntent().getExtras();
String flash_mode = extras.getString("FLASH");
FLASH_MODE = flash_mode;
boolean front_cam_req = extras.getBoolean("Front_Request");
isFrontCamRequest = front_cam_req;

sv = (SurfaceView) findViewById(R.id.camera_preview);

// Get a surface
sHolder = sv.getHolder();

// add the callback interface methods defined below as the Surface
// View
// callbacks
sHolder.addCallback(this);

// tells Android that this surface will have its data constantly
// replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

} else {
// display in long period of time
Toast.makeText(getApplicationContext(),
"Your Device dosen't have a Camera !", Toast.LENGTH_LONG)
.show();
}

}

/** 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;
}
}

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
}

@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// get camera parameters
parameters = mCamera.getParameters();
if (FLASH_MODE == null || FLASH_MODE.isEmpty())
{
FLASH_MODE = "auto";
}
parameters.setFlashMode(FLASH_MODE);

// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();

// sets what code should be executed after the picture is taken
Camera.PictureCallback mCall = new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
Log.d("ImageTakin", "Done");

mCamera.stopPreview();
// release the camera
mCamera.release();
Toast.makeText(getApplicationContext(),
"Your Picture has been taken !", Toast.LENGTH_LONG)
.show();

finish();

}
};

mCamera.takePicture(null, null, mCall);
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw the preview.

mCamera = getCameraInstance();
try {
mCamera.setPreviewDisplay(holder);

} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

}

Then use your Custom Surface View (square view)like This:

 <SurfaceView
android:id="@+id/camera_preview"
android:layout_width="..."
android:layout_height="..."
..... />


Related Topics



Leave a reply



Submit