Get picture from camera - android

Get picture from camera when object(any document)fully occupies the camera view inside the camera boundary. actually i have created custom camera and i want to get any object picture when picture fully come inside camera boundary.I have set the camera boundary inside the xml part.
This is my code please check and correct me fine out this problem.
public class MainActivity extends ActionBarActivity {
private ImageSurfaceView mImageSurfaceView;
private Camera camera;
public static FrameLayout cameraPreviewLayout;
private ImageView capturedImageHolder;
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cameraPreviewLayout = (FrameLayout) findViewById(R.id.camera_preview);
camera = checkDeviceCamera();
mImageSurfaceView = new ImageSurfaceView(MainActivity.this, camera);
cameraPreviewLayout.addView(mImageSurfaceView);
Button captureButton = (Button) findViewById(R.id.button);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
camera.takePicture(null, null, pictureCallback);
}
});
}
private Camera checkDeviceCamera() {
Camera mCamera = null;
try {
mCamera = Camera.open();
} catch (Exception e) {
e.printStackTrace();
}
return mCamera;
}
PictureCallback pictureCallback = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();;
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
Log.e("mediaFile",""+mediaFile.length());
return mediaFile;
}
}
This is the xml file.
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="400dp"
android:layout_height="320dp"
android:background="#drawable/camera_backround"
android:padding="10dp"
android:layout_margin="10dp"
>
</FrameLayout>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/capture_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
This is my SurfaceView class.
public class ImageSurfaceView extends SurfaceView implements SurfaceHolder.Callback,Camera.PictureCallback, Camera.PreviewCallback {
private Camera camera;
private SurfaceHolder surfaceHolder;
Context context;
private boolean mFocused;
private boolean imageProcessorBusy=true;
private int width;
private int height;
public void setImageProcessorBusy(boolean imageProcessorBusy) {
this.imageProcessorBusy = imageProcessorBusy;
}
public ImageSurfaceView(Context context, Camera camera) {
super(context);
this.camera = camera;
this.surfaceHolder = getHolder();
this.surfaceHolder.addCallback(this);
this.surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
this.context=context;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera.setDisplayOrientation(90);
try {
this.camera.setPreviewDisplay(holder);
this.camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
refreshCamera();
Log.e("camera", "surfaceChanged");
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e("camera","surfaceDestroyed");
this.camera.stopPreview();
this.camera.setPreviewCallback(null);
this.camera.release();
this.camera = null;
}
private void refreshCamera() {
try {
Log.e("camera", "refreshCamera");
camera.stopPreview();
} catch (Exception e) {
}
try {
Log.e("camera", "refreshCamera----2");
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
camera.setPreviewCallback(this);
} catch (Exception e) {
}
}
#Override
public void onPictureTaken(byte[] bytes, Camera camera) {
android.hardware.Camera.Size pictureSize = camera.getParameters().getPictureSize();
Log.d("Check", "onPictureTaken - received image " + pictureSize.width + "x" + pictureSize.height);
}
#Override
public void onPreviewFrame(byte[] data, Camera camera) {
android.hardware.Camera.Size pictureSize = camera.getParameters().getPreviewSize();
// layout in the activity that the cameraView will placed in
int layoutWidth = MainActivity.cameraPreviewLayout.getWidth();
int layoutHeight = MainActivity.cameraPreviewLayout.getHeight();
Log.e("layoutWidth","------"+layoutWidth);
Log.e("layoutHeight", "---------" + layoutHeight);
Log.d("onPreviewFrame", "onPreviewFrame - received image " + pictureSize.width + "x" + pictureSize.height
+ " focused: "+ mFocused +" imageprocessor: "+(imageProcessorBusy?"busy":"available"));
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
width = MeasureSpec.getSize(widthMeasureSpec);
height = width;
setMeasuredDimension(width, width);
}
}

you can use intent to capture the image data from camera, try this
private static final int TAKE_PICTURE = 1000;
private Uri imageUri;
In your button click
Button captureButton = (Button) findViewById(R.id.button);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
public void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
Your xml code
<ImageView
android:id="#+id/Imageview"
android:layout_width="400dp"
android:layout_height="320dp"
android:background="#drawable/camera_backround"
android:padding="10dp"
android:layout_margin="10dp"
/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/capture_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
Note: if you are going to take multiple pictures append timestamp to the filename.

Related

Front Camera opening in the side in small view - Android

I am implementing android-gpuimage library in my code.
https://github.com/CyberAgent/android-gpuimage
I used the camera code of the sample project. Everyting works fine, but whenever I switch the camera, front camera opens in the side in a small view. I want the front camera to occupy the whole Surfaceview.
Here is my code:
public class CameraActivity extends Activity implements OnSeekBarChangeListener, OnClickListener {
private GPUImage mGPUImage;
private CameraHelper mCameraHelper;
private CameraLoader mCamera;
private GPUImageFilter mFilter;
private int cameraId;
private FilterAdjuster mFilterAdjuster;
static int camerastate=0;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
((SeekBar) findViewById(R.id.seekBar)).setOnSeekBarChangeListener(this);
findViewById(R.id.filter).setOnClickListener(this);
findViewById(R.id.flipCamera).setOnClickListener(this);
findViewById(R.id.captureImage).setOnClickListener(this);
cameraId = CameraInfo.CAMERA_FACING_BACK;
mGPUImage = new GPUImage(this);
mGPUImage.setImage(mImage);
mGPUImage.setFilter(mGPUImageFilter);
mGPUImage.getBitmapWithFilterApplied();*/
mGPUImage.setGLSurfaceView((GLSurfaceView) findViewById(R.id.surfaceView));
mCameraHelper = new CameraHelper(this);
mCamera = new CameraLoader();
}
#Override
protected void onResume() {
super.onResume();
mCamera.onResume();
}
#Override
protected void onPause() {
mCamera.onPause();
super.onPause();
}
#Override
public void onClick(final View v) {
switch (v.getId()) {
case R.id.filter:
GPUImageFilterTools.showDialog(this, new OnGpuImageFilterChosenListener() {
#Override
public void onGpuImageFilterChosenListener(final GPUImageFilter filter) {
switchFilterTo(filter);
}
});
break;
case R.id.captureImage:
if (mCamera.mCameraInstance.getParameters().getFocusMode().equals(
Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
takePicture();
} else {
mCamera.mCameraInstance.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(final boolean success, final Camera camera) {
takePicture();
}
});
}
break;
case R.id.flipCamera:
mCamera.switchCamera();
break;
}
}
private void takePicture() {
// TODO get a size that is about the size of the screen
Camera.Parameters params = mCamera.mCameraInstance.getParameters();
params.setRotation(90);
mCamera.mCameraInstance.setParameters(params);
for (Camera.Size size : params.getSupportedPictureSizes()) {
Log.i("ASDF", "Supported: " + size.width + "x" + size.height);
}
mCamera.mCameraInstance.takePicture(null, null,
new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, final Camera camera) {
final File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d("ASDF",
"Error creating media file, check storage permissions");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("ASDF", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("ASDF", "Error accessing file: " + e.getMessage());
}
data = null;
Bitmap bitmap = BitmapFactory.decodeFile(pictureFile.getAbsolutePath());
mGPUImage1.setImage(pictureFile);
mGPUImage1.setFilter(new GPUImageSepiaFilter());
final GLSurfaceView view = (GLSurfaceView) findViewById(R.id.surfaceView);
view.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
mGPUImage1.saveToPictures(bitmap1, "GPUImage",
System.currentTimeMillis() + ".jpg",
new OnPictureSavedListener() {
#Override
public void onPictureSaved(final Uri
uri) {
pictureFile.delete();
camera.startPreview();
view.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
}
});
Log.e("Activity", "GPUIMAGE " + mGPUImage.toString());
}
});
}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static File getOutputMediaFile(final int type) {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
private void switchFilterTo(final GPUImageFilter filter) {
if (mFilter == null
|| (filter != null && !mFilter.getClass().equals(filter.getClass()))) {
mFilter = filter;
mGPUImage.setFilter(mFilter);
mFilterAdjuster = new FilterAdjuster(mFilter);
}
}
#Override
public void onProgressChanged(final SeekBar seekBar, final int progress,
final boolean fromUser) {
if (mFilterAdjuster != null) {
mFilterAdjuster.adjust(progress);
}
}
#Override
public void onStartTrackingTouch(final SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(final SeekBar seekBar) {
}
private class CameraLoader {
int mCurrentCameraId = 0;
Camera mCameraInstance;
public void onResume() {
setUpCamera(mCurrentCameraId);
}
public void onPause() {
releaseCamera();
}
public void switchCamera() {
releaseCamera();
mCurrentCameraId = (mCurrentCameraId + 1) % mCameraHelper.getNumberOfCameras();
setUpCamera(mCurrentCameraId);
}
private void setUpCamera(int id) {
Log.e("Activity", "ID1 " + id);
mCameraInstance = getCameraInstance(id);
Camera.Parameters parameters = mCameraInstance.getParameters();
// TODO adjust by getting supportedPreviewSizes and then choosing
// the best one for screen size (best fill screen)
if (parameters.getSupportedFocusModes().contains(
Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
parameters.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
parameters.setPictureSize(640,480);
mCameraInstance.setParameters(parameters);
int orientation = mCameraHelper.getCameraDisplayOrientation(
CameraActivity.this, mCurrentCameraId);
CameraInfo2 cameraInfo = new CameraInfo2();
mCameraHelper.getCameraInfo(mCurrentCameraId, cameraInfo);
boolean flipHorizontal = cameraInfo.facing == CameraInfo.CAMERA_FACING_FRONT;
mGPUImage.setUpCamera(mCameraInstance, orientation, flipHorizontal, false);
}
/** A safe way to get an instance of the Camera object. */
private Camera getCameraInstance(int id) {
Camera c = null;
Log.e("Activity","Camera Instance " + id);
try {
c = mCameraHelper.openCamera(id);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
private void releaseCamera() {
mCameraInstance.setPreviewCallback(null);
mCameraInstance.stopPreview();
mCameraInstance.release();
mCameraInstance= null;
}
}
}
EDIT:
SCreenshot of my camera: when i press the switch camera button, the back view stops and my front view starts in the corner.
i tested it in other device. The switchcamera feature is working perfectly.but, it is not working correctly in some devices.
This will surely fix your issue :
**How to switch**
public void switchCamera() {
releaseCamera();
mCameraId = (mCameraId + 1) % Camera.getNumberOfCameras();
**mGpuImageView.reInitLayout();**//the trick
prepareCamera();
}
**releaseCamera**
private void releaseCamera() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
}
**prepareCamera**
your camera prepare method
**mGpuImageView.reInitLayout**
//Put this inside your GPUImageView.java class
public void reInitLayout() {
mGLSurfaceView.requestLayout();
mGPUImage.deleteImage();
}
Let me know if you face any further issue.
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Set this for fill_parent and check.
Could you check this and paste screen
<ImageView
android:id="#+id/img_switch_camera"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_gravity="center"
android:layout_weight="0.08"
android:src="#drawable/ic_switch_camera" />
It supose to change size for 300x300

How can draw rectangle on camera preview?

Hi aim working n android application to detect page number using camera preview.
After i received frame from OnPreviewFrame i'm doing real time image processing using opencv to find page number position .Now my question is How can i draw rectangle on surface View ?
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
<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>
Add the Permissions also

Android Custom Camera touch to take picture

I've created a custom camera that takes a photo within a frame. however i dont intend to use a button to capture a photo but rather an ontouch event. Ive tried a couple of times but as soon as i put an onTouchListener, it crashes. Should i use gesture?
Here is my code.
MainActivity -
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
private File pictureFile;
private Drawable d2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView iv = new ImageView(this);
iv.setImageResource(R.drawable.richard2);
mCamera = getCameraInstance();
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
// final ImageView view = (ImageView) findViewById(R.id.imageView1);
preview.addView(mCameraPreview);
preview.addView(iv);
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
//File file1 = getOutputMediaFile();
//Bitmap myBitmap = BitmapFactory.decodeFile(file1.getAbsolutePath());
//Drawable drawable = new BitmapDrawable(getResources(), myBitmap);
//view.setBackground(R.drawable.drawable);
//view.setImageBitmap(myBitmap);
}
});
}
/**
* Helper method to access the camera returns null if it cannot get the
* camera or does not exist
*
* #return
*/
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}
the camera class -
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
lastly, the xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/container"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<Button
android:id="#+id/button_capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="9419K" />
</LinearLayout>
one thing i didnt try was to put an onclick listener, so turns out, it works.
preview.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
});

Take Picture through custom camera and store to show on next activity

How to take and save image on click using Custom camera and show the saved image on next Activity's Screen. (with PostTask )
Here is the what i have tried...
1.Camera Activity
public static final int CAMERA_REQUEST = 1000;
private FrameLayout cameraPreview;
private Camera mCamera;
private CameraPreview mCameraPreview;
private Camera_Activity screen;
private final Context context = this;
capture_snap.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
PostTask pt = new PostTask();
pt.execute(screen);
pdialog = new ProgressDialog(Camera_Activity.this);
pdialog.setCancelable(false);
pdialog.setMessage("Please Wait...");
pdialog.show();*/
}
});
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
System.out.println("picture file is null");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpeg");
return mediaFile;
}
private class PostTask extends AsyncTask<Activity, String, String>
{
#Override
protected String doInBackground(Activity... params) {
return "";
}
protected void onPostExecute(String result) {
if(pdialog != null)
{
pdialog.setCancelable(true);
pdialog.dismiss();
Intent i=new Intent(getApplicationContext(),Camera_view.class);
//i.putExtra(mediaFile, mediaFile);
startActivity(i);
}
else{
pdialog.setCancelable(true);
pdialog.dismiss();
MessageDialog.showMessage("Alert",
"Incorrect Path", Camera_Activity.screen);
}
}
}
private void releaseCamera(){
if (mCamera != null){
mCameraPreview.getHolder().removeCallback(mCameraPreview);
mCamera.release(); // release the camera for other applications
}
}
2.Camera Preivew
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
// Constructor that obtains context and camera
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera) {
super(context);
this.mCamera = camera;
this.mSurfaceHolder = this.getHolder();
this.mSurfaceHolder.addCallback(this);
this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
// left blank for now
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
//mCamera.stopPreview();
//mCamera.release();
if(mCamera != null){
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
}
}
public void onPause() {
mCamera.stopPreview();
//mCamera = null;
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
3.Camera View //Here i am trying show captured image...
go through with this tutorial dude
http://www.androidhive.info/2013/09/android-working-with-camera-api/

custom camera in android

In my application I need to use custom camera. There are two buttons on the screen "Keep Image" and "Retake Photo". The picture taken by the cam should be saved in the specified directory when I click on the "keep image" button. When I click on "retake photo" button the cam should be ready to take a new photo. I have searched for the same and I got a Stack overflow link and I tried to implement that in my app, but the problem is all the code for taking picture and saving picture is written in the same class. The picture taken will be automatically saved without even a button click. I want to change that. I have tried different ways but throwing errors.
Please help me...given below is my java code
public class CustomCameraDemo extends Activity {
private SurfaceView preview=null;
private SurfaceHolder previewHolder=null;
public 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;
Button save;
Button retake;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// image=(ImageView)findViewById(R.id.image);
save=(Button)findViewById(R.id.Save);
retake=(Button)findViewById(R.id.Retake);
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());
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
retake.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#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(CustomCameraDemo.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) {
}
};
Camera.PictureCallback photoCallback=new Camera.PictureCallback(){
public void onPictureTaken(final byte[] data, final Camera camera){
dialog=ProgressDialog.show(CustomCameraDemo.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(),"MyMedicalRecords");
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(CustomCameraDemo.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;
}
}
given below is my main layout
<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"
/>
<Button android:layout_width="150dip"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Keep Photo"
android:id="#+id/Save"></Button>
<TextView android:layout_below="#+id/surface"
android:layout_width="wrap_content"
android:id="#+id/textView1"
android:layout_height="wrap_content"
android:text=""
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"></TextView>
<Button android:layout_width="150dip"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/textView1"
android:text="Retake Photo"
android:id="#+id/Retake"></Button> </RelativeLayout>
If you want to build over the existing code, you can just delete the saved image when the user opts to retake another image.

Categories

Resources