Android Custom Camera touch to take picture - android

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);
}
});

Related

Custom camera new captured image overwrites the old one

I have created a custom camera which snaps a picture and stores it in a folder in the internal storage of the phone. But whenever I snap a new picture, it over writes the old one.
MainActivity
public class MainActivity extends AppCompatActivity {
Camera camera;
Button capture, gallery;
FrameLayout frameLayout;
ShowCamera showCamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frameLayout = findViewById(R.id.frameLayout);
capture = findViewById(R.id.button);
gallery = findViewById(R.id.button2);
camera = Camera.open();
showCamera = new ShowCamera(this,camera);
frameLayout.addView(showCamera);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
captureImage(showCamera);
}
},4000);
}
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File picture_file = getOutputMediaFile();
if(picture_file==null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(picture_file);
fos.write(data);
fos.close();
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
};
private File getOutputMediaFile() {
String state = Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED)) {
return null;
}
else {
File folder_gui = new File (Environment.getExternalStorageDirectory() + File.separator+"GUI");
if(!folder_gui.exists()) {
folder_gui.mkdirs();
}
File outputFile = new File(folder_gui,"temp.jpg");
return outputFile;
}
}
public void captureImage(View v) {
if(camera!=null) {
camera.takePicture(null,null,mPictureCallback);
}
}
}
ShowCamera
public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback{
Camera camera;
SurfaceHolder holder;
public ShowCamera(Context context, Camera camera) {
super(context);
this.camera = camera;
holder = getHolder();
holder.addCallback(this);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Camera.Parameters params = camera.getParameters();
//change the orientation of the camera
List<Camera.Size> sizes = params.getSupportedPictureSizes();
Camera.Size mSize = null;
for(Camera.Size size : sizes) {
mSize = size;
}
if(this.getResources().getConfiguration().orientation!= Configuration.ORIENTATION_LANDSCAPE) {
params.set("orientation","portrait");
camera.setDisplayOrientation(90);
params.setRotation(90);
}
else {
params.set("orientation","landscape");
camera.setDisplayOrientation(0);
params.setRotation(0);
}
params.setPictureSize(mSize.width,mSize.height);
camera.setParameters(params);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When a new picture is snapped, I want that picture to be added in the folder instead of overwriting the existing one. How do I do this?
Replace the code with this
private File getOutputMediaFile() {
String state = Environment.getExternalStorageState();
if(!state.equals(Environment.MEDIA_MOUNTED)) {
return null;
}
else {
File folder_gui = new File (Environment.getExternalStorageDirectory() + File.separator+"GUI");
if(!folder_gui.exists()) {
folder_gui.mkdirs();
}
File outputFile = new File(folder_gui,System.currentTimeInMillies()+."jpg");
return outputFile;
}
}
Because you provide the same name at every time so it will replace your old file

How to hide SurfaceView when button is clicked?

I want to do is,in an activity with SurfaceView that open Camera,and preview inside it.After click a button,the SurfaceView stop/invisible,so the image capture will shown on the ImageView in the activity.
Is as the diagram below:
So I have a custom camera activity which have the XML like below,
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<SurfaceView
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/showImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible" />
<FloatingActionButton
android:id="#+id/cameraButton"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_centerHorizontal="true" />
</FrameLayout>
What I wanna to do is,when I click on the floating button,the SurfaceView disappear,ImageView visible,then the image that taken by the camera shown on the ImageView.
So what I have tried so far
public class CameraActivity extends AppCompatActivity implements
SurfaceHolder.Callback {
Camera mCamera;
Camera.PictureCallback jpegCallback;
ImageView showImage;
FloatingActionButton btnCamera;
SurfaceHolder surfaceHolder;
SurfaceView surfaceView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
btnCamera = (FloatingActionButton) findViewById(R.id.cameraButton);
surfaceView = (SurfaceView)findViewById(R.id.surface_view);
showImage = (ImageView)findViewById(R.id.showImage);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here when click the camera button
//camera take photo
//surface view disappear
//preview image shown on image view
mCamera.takePicture(null,null,jpegCallback);
showImage.setVisibility(View.VISIBLE);
surfaceView.setVisibility(View.INVISIBLE);
}
});
jpegCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outputStream = null;
File file_image = getDirs();
if(!file_image.exists() && !file_image.mkdirs()){
Toast.makeText(getApplicationContext(),"Failed to save picture",Toast.LENGTH_LONG).show();
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String date = simpleDateFormat.format(new Date());
String photofile = "myphotos" + date+ ".jpg";
String file_name = file_image.getAbsolutePath() + "/" + photofile;
File picFile = new File(file_name);
Bitmap bitmap = null;
try{
outputStream = new FileOutputStream(picFile);
outputStream.write(data);
outputStream.close();
//here set the picture capture to the image view
//convert it to bitmap,setBitmap to the imageView
bitmap = decodeFile(picFile,10);
if(bitmap !=null){
showImage.setImageBitmap(bitmap);
Toast.makeText(CameraActivity.this,
"Picture Captured Successfully:", Toast.LENGTH_LONG)
.show();
}else {
Toast.makeText(CameraActivity.this,
"Failed to Capture the picture. kindly Try Again:",
Toast.LENGTH_LONG).show();
}
} catch (IOException e){
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),"Picture saved",Toast.LENGTH_LONG).show();
refreshCamera();
}
};
}
private void refreshCamera() {
if(surfaceHolder.getSurface() == null){
return;
}
//stop the camera preview
try{
mCamera.stopPreview();
}catch (Exception e){
e.printStackTrace();
}
//start camera again
try{
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
//open camera
try{
mCamera = Camera.open();
}catch (RuntimeException ex){
ex.printStackTrace();
}
Camera.Parameters parameters;
parameters = mCamera.getParameters();
parameters.setPreviewFrameRate(20);
parameters.setPreviewSize(352,288);
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(90);
try{
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
refreshCamera();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
mCamera= null;
}
}
After trying this,what I got now is,the screen is totally blank.SurfaceView is invisible,ImageView with preview of the image taken from camera not shown out.
But I checked file_name and bitmap is having value in the log.
So I tried,to not set the SurfaceView to invisible like below:
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraImage();
showImage.setVisibility(View.VISIBLE);
//surfaceView.setVisibility(View.INVISIBLE);
}
});
The image can shown on the on the top on surface view like below,but if I set the surface view to invisible,the whole screen appear blank.
But I want the surface view disappear,only the ImageView available.
Moving following line (to make surface view invisible),
surfaceView.setVisibility(View.INVISIBLE);
from onClick(View v) method to onPictureTaken(byte[] data, Camera camera) method would solve the problem.
But, that would result in camera release and it must be opened again to capture another picture.

Get picture from camera

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.

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/

Android Camera Take Picture and SAVE or send to next activity

I’m a beginner and I need help. How do I take photos with camera and save or send to next activity?
I've tried a couple of options, i.e. takepicture with picture callback and surfaceview/take with intent. However, neither works properly on Android 2.3.3. Could someone figure out the issues with my code below?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sf_foto);
mCamera = getCameraInstance();
mCameraPreview = new SF_CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
ImageButton captureButton = (ImageButton) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(myShutterCallback, mPicture_RAW, mPicture);
}
});
}
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open(0);
camera.setDisplayOrientation(90);
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {}
};
PictureCallback mPicture_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {}
};
PictureCallback mPicture = 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.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent i = new Intent(StyloveFoto.this, Filter.class);
startActivity(i);
}
};
protected File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"KWAlbum");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("KWAlbum", "failed to create directory");
return null;
}
}
// Create a media file name
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "KW" + ".jpg");
return mediaFile;
}
my surface view:
public class SF_CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
public SF_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();
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
mCamera.setPreviewDisplay(surfaceHolder);
Camera.Parameters parameters = mCamera.getParameters();
parameters.set("orientation", "portrait");
mCamera.setParameters(parameters);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
}
instead of this line : fos.write(data);
write : fos.write(data,0,data.length);
if you want to pass it to the next activity:
Intent i = new Intent(StyloveFoto.this, Filter.class);
i.putExtra("myImage",data);
startActivity(i);
and then in class filter in the oncreate method
byte[] myImage = getIntent()getIntent().getByteArrayExtra("myImage");
I got the same problem and i just solve it before.
The problem is that mPicture is an object of PictureCallback. You can't set intent directing to Filter.class from StyloveFoto.this, because it is in PictureCallback interface. Try this one:
Intent i = new Intent(getBaseContext() , Filter.class);
startActivity(i);
Such a big trap in java....hope it helps :)
Either you save the picture like this and pass the path to another activity
final File file = new File(Environment.getExternalStorageDirectory() + "/" + System.currentTimeMillis() + "_pic.jpg");
OutputStream output = null;
try {
output = new FileOutputStream(file);
output.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != output) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
OR
Pass data from camera activity :
Intent intent = new Intent(getApplicationContext(), your_class.class);
intent.putExtra("path", path);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Receiving Activity
byte[] data = getIntent().getByteArrayExtra("path");
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
image.setImageBitmap(scaleDownBitmapImage(bitmap, 300, 200));

Categories

Resources