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.
Related
This question already has answers here:
How do I open the "front camera" on the Android platform?
(10 answers)
Closed 5 years ago.
i need Some Help help I am Working With An app which Can take picture automatic On Activity With Main Camera But I want to use Front Camera Instead Of Main Camera
can U Please Tell Me How To use Front Camera
here Is My Code
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;
//Camera variables
//a surface holder
private SurfaceHolder sHolder;
//a variable to control the camera
private Camera mCamera;
//the camera parameters
private Parameters parameters;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//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
sv = (SurfaceView) findViewById(R.id.surfaceView);
//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);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
//get camera parameters
parameters = mCamera.getParameters();
//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
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
//set the iv_image
iv_image.setImageBitmap(bmp);
TakePicture t=new TakePicture();
t.SaveBitmap(bmp);
// SendEmail(bmp);
}
};
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 = Camera.open();
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
//stop the preview
mCamera.stopPreview();
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
public void openFrontFacingCamera() {
numberOfCamera = Camera.getNumberOfCameras();
if(camId == Camera.CameraInfo.CAMERA_FACING_BACK){
camId = Camera.CameraInfo.CAMERA_FACING_FRONT;
Toast.makeText(getApplicationContext(), "BACK TO FRONT" ,
1000).show();
try {
camera.release();
camera = Camera.open(camId);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (RuntimeException e) {
} catch (IOException e) {}
}else if(camId == Camera.CameraInfo.CAMERA_FACING_FRONT){
camId = Camera.CameraInfo.CAMERA_FACING_BACK;
Toast.makeText(getApplicationContext(), "FRONT TO BACK" ,
1000).show();
try {
camera.release();
camera = Camera.open(camId);
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (RuntimeException e) {
} catch (IOException e) {}
}
}
hope this function will help u
change
mCamera = Camera.open();
to
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
I have made a simple Custom Camera app. Now i want to add my own buttons on camera screen. How can i do it. Here is my layout.xml code.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<FrameLayout
android:id="#+id/framelayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="21dp"
android:layout_weight="1" >
<Button android:id="#+id/but2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</FrameLayout>
</LinearLayout>
your xml file , Main.xml
<?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/layout">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="Camera Demo"
android:textSize="24sp" />
<FrameLayout android:id="#+id/preview"
android:layout_weight="1" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</FrameLayout>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/buttonClick"
android:text="Click" android:layout_gravity="center"></Button>
</LinearLayout>
your preview class,
class Preview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";
SurfaceHolder mHolder;
public Camera camera;
Preview(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
camera.stopPreview();
camera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
// parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p= new Paint(Color.RED);
Log.d(TAG,"draw");
canvas.drawText("PREVIEW", canvas.getWidth()/2, canvas.getHeight()/2, p );
}
}
and CameraDemo.class
public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preview = new Preview(this);
((FrameLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
long time = 0;
try {
// write to local sandbox file system
// outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to sdcard
time = System.currentTimeMillis();
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg",time));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
Hope this will help you
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);
}
});
I am developing this app which requires access to the camera. I have accessed it well. But there are two issues.
The preview is all stretched when the phone is vertical. Secondly, the camera preview isn't visible when I resume the app. The camera.open() function does opens the camera but I am not able to see the preview. I have tried all the help available on the forum but nothing is actually solving my problem.
-Thanks in advance!
//Camera Activity file
#SuppressLint("SimpleDateFormat")
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
private FrameLayout preview;
private Button bCapture;
private Button bGallery;
private static final String TAG = "CameraActivity";
private static final int PICK_IMAGE_REQUEST = 1;
private TextView tvCheck;
public final static String EXTRA_MESSAGE = "com.epfl.mycamera.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_camera);
if (checkCameraHardware(getBaseContext())){
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera, CameraActivity.this);
preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
//Adding Camera Button
bCapture = (Button) findViewById(R.id.bCapture);
//Button Listener for storing images
bCapture.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, null, jpegCallback);
mCamera.startPreview();
Log.d(TAG, "takePicture");
}
});
//Adding Gallery Button
bGallery = (Button) findViewById (R.id.bGallery);
bGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvCheck = (TextView) findViewById (R.id.tvCheck);
selectImageFromGallery();
}
});
}
Log.d(TAG, "OnCreate");
}
/******************************************************************/
public void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int aRequestCode, int aResultCode, Intent aData) {
switch (aRequestCode) {
case PICK_IMAGE_REQUEST:
handleImage(aData);
break;
default:
tvCheck.setText("You can only select images.");
break;
}
super.onActivityResult(aRequestCode, aResultCode, aData);
}
private void handleImage(Intent aData) {
if ((aData != null) && (aData.getData() != null)) {
Uri selectedImage = aData.getData();
String[] filePathColumn = {MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
Log.d("ImageActivity", "After extracting file Path");
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Log.d("ImageActivity", "After closing the cursor");
setContentView(R.layout.activity_image_old); //setting the view to the image
ImageView imgView = (ImageView) findViewById(R.id.ivGallery);
imgView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Button bLiveCamera = (Button) findViewById(R.id.bCameraPreview);
bLiveCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.activity_camera);
mCamera.startPreview();
}
});
}
else {
tvCheck.setText("You did not select an image");
}
}
/****************************************************************/
/** Stores jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
try {
File mediaStorageDir = new File(Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCamera");
// Saving image to the SD CARD with a file operation
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg");
FileOutputStream outStream = new FileOutputStream(mediaFile);
outStream.write(data);
outStream.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
} Log.d(TAG, "onPictureTaken - jpeg");
}
};
/***************************************************************/
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
Log.d(TAG, "Camera Available");
return true;
} else {
Log.d(TAG, "No Camera Found");
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public Camera getCameraInstance(){
Camera c = null;
try {
int i = Camera.getNumberOfCameras();
releaseCamera(); //in case camera is being accessed by any other app.
Log.d(TAG, "Number of Cameras "+i +"\n");
c = Camera.open(); // attempt to get a Camera instance
Log.d(TAG, "Camera Opened");
}
catch (Exception e){
Log.d(TAG, "Camera Can't Be Accessed");
}
return c; // returns null if camera is unavailable
}
#Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mPreview.getHolder().removeCallback(mPreview);
mCamera.release(); // release the camera for other applications
}
}
#Override
public void onResume() {
super.onResume();
// Get the Camera instance as the activity achieves full user focus
if (mCamera == null) {
getCameraInstance();
mCamera.startPreview();
}
}
}
this is my camera preview class:
#SuppressLint({ "ViewConstructor", "SdCardPath" })
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private SurfaceHolder mHolder;
private Camera mCamera;
private Size mPreviewSize;
// private Activity CameraActivity;
#SuppressWarnings("deprecation")
public CameraPreview(Context context, Camera camera, Activity activity) {
super(context);
mCamera = camera;
//CameraActivity = activity;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
//add camera preview call back here.
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try{
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
Camera.Parameters parameters = mCamera.getParameters();
List<Size> localSizes = mCamera.getParameters().getSupportedPreviewSizes();
mPreviewSize = localSizes.get(0);
Log.d(TAG, "Width " + mPreviewSize.width);
Log.d(TAG, "Height " + mPreviewSize.height);
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height );
mHolder.setFixedSize(mPreviewSize.width, mPreviewSize.height);
requestLayout();
mCamera.setParameters(parameters);
//start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.setDisplayOrientation(90);
//setCameraDisplayOrientation(CameraActivity, 0, mCamera);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
You create a CameraPreview only onCreate() of your Activity. But the camera instance is released onPause(), and a new one is opened onResume(). Therefore, you need to set the surface again.
I am using android 1.5.
Here is my image capture code :
public class CaptureImage extends Activity implements SurfaceHolder.Callback{
private Camera camera=null;
private SurfaceHolder surfaceHolder = null;
private boolean previewRunning = false;
private Context thisContext = this;
private String imageName = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.image_capture);
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btn =(Button) findViewById(R.id.capture_image_btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
camera.takePicture(null, picCalBac, picCalBac);
}
});
}
Camera.PictureCallback picCalBac = new PictureCallback() {
#Override
public void onPictureTaken(byte[] paramArrayOfByte, Camera paramCamera) {
if (paramArrayOfByte != null) {
//Intent intent = new Intent();
//imageName = "myImg.jpg";
//storeByteImage(thisContext, paramArrayOfByte, 75, imageName);
//setResult(RESULT_OK, intent);
//finish();
}
}
};
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
if (previewRunning) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(arg2, arg3);
p.setPictureSize(800, 600);
camera.setParameters(p);
try {
camera.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
Log.d("IOException", e.getMessage());
}
camera.startPreview();
previewRunning = true;
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
camera.stopPreview();
previewRunning = false;
camera.release();
}
private boolean storeByteImage(Context mContext, byte[] imageData,
int quality, String expName) {
FileOutputStream fileOutputStream = null;
try {
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap myImage = BitmapFactory.decodeByteArray(imageData, 0,
imageData.length,options);
fileOutputStream = openFileOutput(imageName, Context.MODE_PRIVATE);
BufferedOutputStream bos = new BufferedOutputStream(
fileOutputStream);
myImage.compress(CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Log.d("FileNotFoundException", e.getMessage());
} catch (IOException e) {
Log.d("IOException", e.getMessage());
}
return true;
}
Here is my image_capture.xml :
<?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:orientation="vertical">
<SurfaceView android:id="#+id/surface_camera"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:layout_weight="1">
</SurfaceView>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:text="Capture" android:gravity="center_horizontal"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="#+id/capture_image_btn" />
</LinearLayout>
</LinearLayout>
I have added user permission in manifest.xml.
This code is accessed onClick from another activity. And after I click the photo the screen remains still with clicked snapshot. The issue is the camera window is very small about 40% of height and width and the preview shown after image is clicked is also smaller, about 80% of height and width. How to make both (camera window and preview after click) full screen ?
Solved this by adding the following code onCreate
surfaceHolder.setFixedSize(getWindow().getWindowManager()
.getDefaultDisplay().getWidth(), getWindow().getWindowManager()
.getDefaultDisplay().getHeight());