Android Front Camera image is not being saved properly - android

I am trying to make selfie application. I captured image and saved it from front camera. But in gallery or from file manager image is not being open.
"cannot load image" this message is coming. If i change flag from front camera to back camera it is perfectly working.
public class Preview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
private Context context;
private String TAG = "Preview";
public Preview(Camera mCamera, Context context) {
super(context);
this.mCamera = mCamera;
this.context = context;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
#Override
public void surfaceCreated(SurfaceHolder mHolder) {
safeCameraOpen();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
mCamera.release();
mCamera = null;
}
} else {
Log.d(TAG, "Error in camera : ");
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (mCamera != null) {
setCameraDisplayOrientation((Activity) context, mCamera);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCameraAndPreview();
}
// This method is called while clicking for selfie
public void captureImage() {
mCamera.takePicture(null, null, mPicture);
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
saveImage(data);
}
};
public void saveImage(byte[] data) {
try {
File imageFile = createImageFile();
if (imageFile != null) {
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(data);
fos.close();
Toast.makeText(context, "New Image saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Directory problem", Toast.LENGTH_LONG).show();
}
} catch (Exception error) {
error.getMessage();
Toast.makeText(context, "Image could not be saved.", Toast.LENGTH_LONG).show();
}
}
private File createImageFile() throws IOException {
// Create an image file name
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Selfie");
if (!storageDir.exists() && !storageDir.mkdirs()) {
Log.d(TAG, "Can't create directory to save image.");
Toast.makeText(context, "Can't create directory to save image.", Toast.LENGTH_LONG).show();
return null;
}
File image = File.createTempFile(String.valueOf(System.currentTimeMillis()), /* prefix */ ".jpg", /* suffix */ storageDir /* directory */);
return image;
}
private boolean safeCameraOpen() {
boolean qOpened = false;
try {
releaseCameraAndPreview();
mCamera = openFrontFacing();
qOpened = (mCamera != null);
} catch (Exception e) {
e.printStackTrace();
}
return qOpened;
}
public void releaseCameraAndPreview() {
// mPreview.setCamera(null);
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
private Camera openFrontFacing() {
int cameraCount = 0;
Camera camera = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
camera = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e(TAG, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return camera;
}
}
in openFrontFacing() method if i change CAMERA_FACING_FRONT to CAMERA_FACING_BACK it is working perfectly.

every camera has some supported preview sizes and picture sizes, you have to set the correct ones. Its a bit longer topic, search for mCamera.getParameters().getSupportedPictureSizes(); and mCamera.getParameters().getSupportedPreviewSizes();

Related

Camera is being used after Camera.release was called android

I know there are some similar subjects connecting to this but I couldn't solve mine. anyway,I am trying to make some front camera with "flash" where I am calling Camera.release only once in the whole activities, when surfaceDestroyed(). so here is my MainActivity:
#SuppressWarnings("deprecation")
public class MainActivity extends AppCompatActivity {
private Camera mCamera = null;
private CameraPreview mCameraView = null;
private int cameraId = 0;
private void addView() {
if (!getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
.show();
} else {
cameraId = findFrontFacingCamera();
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",
Toast.LENGTH_LONG).show();
} else {
try {
mCamera = Camera.open(cameraId);
} catch (Exception e) {
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
}
}
if (mCamera != null) {
mCameraView = new CameraPreview(this, mCamera);//create a SurfaceView to show camera data
FrameLayout camera_view = (FrameLayout) findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addView();
ImageButton imgCapture = (ImageButton) findViewById(R.id.imgCapture);
imgCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);
setContentView(R.layout.whitescreen);
new CountDownTimer(3000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
if (CameraPreview.safeToTakePicture) {
CameraPreview.safeToTakePicture = false;
mCamera.takePicture(null, null,
new PhotoHandler(getApplicationContext()));
}
setContentView(R.layout.activity_main);
addView();
}
}.start();
}
});
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
Log.d("Camera", "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
}
When pressing the capture button I switch the layout to an empty one(white layout), wait 3 seconds take a picture and then add the camera view again, here is my CameraPreview class:
#SuppressWarnings("deprecation")
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public static boolean safeToTakePicture = false;
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
mCamera.setDisplayOrientation(90);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceCreated " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
if (mHolder.getSurface() == null)
return;
try {
mCamera.stopPreview();
} catch (Exception e) {
Log.d("ERROR", "Trying the camera and it's not running");
}
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
safeToTakePicture = true;
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}
}
I get the error Camera is being used after Camera.release was called a lot of times, for example when taking a picture:
07-02 14:49:35.561 19017-19017/davidandguy.com.selfielightcamera E/AndroidRuntime: FATAL EXCEPTION: main
Process: davidandguy.com.selfielightcamera, PID: 19017
java.lang.RuntimeException: Camera is being used after Camera.release() was called
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1523)
at android.hardware.Camera.takePicture(Camera.java:1468)
at davidandguy.com.selfielightcamera.MainActivity$1$1.onFinish(MainActivity.java:65)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Or even when onResume() is called, for example, minimize the activity and then run again. I know I need to put somewhere onPause() and onResume() but I don't know where/how to implement it. thanks
This is really overdue but as I managed to solve a similar problem of mine a minute ago, I thought I'd contribute for the benefit of yourself and anyone else who might be desperately searching Stack.
I cant see your lifecycle code here , but heres what worked for me, surfaceDestroyed was empty in my case
Firstly, the cameraPreview
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {
try {
this.mCamera.setPreviewDisplay(surfaceHolder);
this.mCamera.startPreview();
} catch (Exception e) {
}
}
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
//TODO we need this here too because on SurfaceCreated we always need to open the camera, in case its released
this.mCamera.setPreviewDisplay(surfaceHolder);
this.mCamera.setDisplayOrientation(90);
//this.mCamera.startPreview();
} catch (IOException e) {
}
}
Next, the CameraActivity
#Override
public void onResume() {
super.onResume();
try{
mCamera = openFrontFacingCameraGingerbread();
// Add to Framelayout
this.mCameraPreview = new CameraPreview(this, this.mCamera);
mImage.removeAllViews();
this.mImage.addView(this.mCameraPreview);
}catch (RuntimeException ex){
}
}
#Override
public void onPause() {
super.onPause();
captureButton.setText("Begin Capture");
if(CameraActivity.this.timer !=null) {
CameraActivity.this.timer.cancel();
CameraActivity.this.timer.purge();
CameraActivity.this.timer = null;
}
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCameraPreview.getHolder().removeCallback(mCameraPreview);
mCamera.release();
mCamera = null;
}
}
#Override
protected void onDestroy(){
super.onDestroy();
releaseCameraAndPreview();
}
private void releaseCameraAndPreview() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if(mCameraPreview != null){
mCameraPreview.destroyDrawingCache();
mCameraPreview.mCamera = null;
}
}

Switching custom camera android causes application to crash

I making a custom camera android application . I have added a button to switch between cameras in my activity . On clicking that button , my camera gets switched perfectly, But when i try to save the image through the callback ,My app crashes due to NullPointerException. Here is my code . Please help me.
Thank You in advance
Camera Activity Code
public class CameraActivity extends Activity {
private Camera mCamera;
private CameraHandler surface_view;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
public static final String TAG="Aloo";
Bitmap bmp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
if(checkifCamera(this))
{
mCamera=getCameraInstance();
surface_view = new CameraHandler(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(surface_view);
}
else
{
Toast.makeText(this,"Sorry camera is not supported on your device",Toast.LENGTH_LONG).show();
}
}
private boolean checkifCamera(Context context)
{
if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
return true;
}
else {
return false;
}
}
public Camera getCameraInstance()
{
Toast.makeText(this,"Chrj",Toast.LENGTH_LONG).show();
Camera c=null;
try{
releaseCameraAndPreview();
c=Camera.open();
}
catch (Exception e)
{
Toast.makeText(this,"Print error"+e.getMessage(),Toast.LENGTH_LONG).show();
return c;
}
Toast.makeText(this,"Check this out "+c,Toast.LENGTH_LONG).show();
return c;
}
public void switchC(View view)//Function called to switch camera
{
surface_view.switchCamera();
mCamera=getCameraInstance();
}
private void releaseCameraAndPreview() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
#Override
protected void onPause() {
super.onPause();
try
{
// release the camera immediately on pause event
//releaseCamera();
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.release();
mCamera = null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void takePH(View view)
{
int toRotate=0;
Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int displayRotation = display.getRotation();
switch (displayRotation) {
case Surface.ROTATION_0: toRotate=90; break;
case Surface.ROTATION_90: break;
case Surface.ROTATION_180: break;
case Surface.ROTATION_270: toRotate=270; break;
}
Toast.makeText(this,"Rotation "+toRotate,Toast.LENGTH_LONG).show();
Camera.Parameters params = mCamera.getParameters();
params.set("rotation",270);
mCamera.setParameters(params);
mCamera.takePicture(null,null,mPicture);
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
Toast.makeText(CameraActivity.this,"Image saves successfully", Toast.LENGTH_LONG).show();
}
};
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(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), "Fotos");
// 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;
}
}
My Custom Camera Handler
public class CameraHandler extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera=null;
public int currentCameraID=0;
public CameraHandler(Context context,Camera camera) {
super(context);
mCamera=camera;
mHolder=getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
Camera.Parameters p = mCamera.getParameters();
}
catch (IOException e)
{
Log.d("--DS", "Error setting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
fixOr();
if(mHolder.getSurface()==null)
{
return;
}
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
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d("--DS", "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
public void fixOr()
{
mCamera.stopPreview();
mCamera.setDisplayOrientation(90);
mCamera.startPreview();
}
public void switchCamera() {
mCamera.stopPreview();
mCamera.release();
if(currentCameraID==Camera.CameraInfo.CAMERA_FACING_BACK)
{
currentCameraID = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else
{
currentCameraID=Camera.CameraInfo.CAMERA_FACING_BACK;
}
mCamera=Camera.open(currentCameraID);
fixOr();
try {
mCamera.setPreviewDisplay(mHolder);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
}
}
I believe my app crashes because when I switch the camera mCamera becomes null. How can I fix that ?
The Error I am getting is:
java.lang.IllegalStateException: Could not execute method of the activity
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'android.hardware.Camera$Parameters android.hardware.Camera.getParameters()'
on a null object reference
After listening to Rami s comment i changed my code in 2 places
1.)
public void switchC(View view)//Function called to switch camera
{
mCamera=surface_view.switchCamera();
}
2.) Switch Camera function
public Camera switchCamera() {
mCamera.stopPreview();
mCamera.release();
if(currentCameraID==Camera.CameraInfo.CAMERA_FACING_BACK)
{
currentCameraID = Camera.CameraInfo.CAMERA_FACING_FRONT;
}
else
{
currentCameraID=Camera.CameraInfo.CAMERA_FACING_BACK;
}
mCamera=Camera.open(currentCameraID);
fixOr();
try {
mCamera.setPreviewDisplay(mHolder);
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
} return mCamera;

Android picture capture from surfaceView

i am try to to capture image,which previews in a surfaceview and there is a button by which picture taken and save onto memory card.preview and capture works well but not able to store on memory card..
there are created file but picture not store one by one...
plz help me...
my try one is here....
public class MainActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
Camera mCamera;
private CameraView cameraview;
RelativeLayout mainlayout;
ImageView capture;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cameraview = new CameraView(this, CameraInfo.CAMERA_FACING_BACK);
setContentView(R.layout.activity_main);
mainlayout = (RelativeLayout) findViewById(R.id.mainlayout);
mainlayout.addView(cameraview);
capture=(ImageView)findViewById(R.id.capture);
/////////////////////////////////////////////////////////
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
capture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
cameraview.mCamera.takePicture(shutterCallback, rawCallback,
jpegCallback);
Toast.makeText(getApplicationContext(), "Captured", 2000).show();
}
});
}
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;
try {
outStream = new FileOutputStream(String.format(
"/sdcard/Demo%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
and my CameraView class is here..
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
Camera mCamera;
int mCameraFacingInfo;
Context m_context;
public CameraView(Context context, int camereface) {
super(context);
// TODO Auto-generated constructor stub
m_context = context;
mCameraFacingInfo = camereface;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (mCamera != null) {
int rotation = ((Activity) m_context).getWindowManager()
.getDefaultDisplay().getRotation();
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) {
mCamera.setDisplayOrientation(90);
} else if (rotation == Surface.ROTATION_90) {
mCamera.setDisplayOrientation(0);
} else if (rotation == Surface.ROTATION_270) {
mCamera.setDisplayOrientation(180);
}
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(width, height);
// mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// ////////////////////////////////////////////////////
/*mCamera.setCameraViewDisplay(holder);
mCamera.setCameraViewCallback(new CameraViewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
//
CameraView.this.invalidate();
}
});
*/
// //////////////////////////////////////////
synchronized (this) {
int cameraFacingInfo = -1;
boolean errorFound = false;
boolean hasFeatCamera = m_context.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (hasFeatCamera) {
try {
cameraFacingInfo = mCameraFacingInfo;
mCamera = Camera.open(cameraFacingInfo);
} catch (Exception e) {
mCamera = Camera.open(0);
}
} else if (CameraInfo.CAMERA_FACING_FRONT > -1) {
try {
cameraFacingInfo = CameraInfo.CAMERA_FACING_FRONT;
mCamera = Camera.open(cameraFacingInfo);
} catch (Exception e) {
errorFound = true;
}
if (errorFound == true) {
try {
mCamera = Camera.open(0);
cameraFacingInfo = 0;
} catch (Exception e) {
cameraFacingInfo = -1;
}
}
}
if (cameraFacingInfo < 0) {
Toast.makeText(m_context, "No camera found.", Toast.LENGTH_LONG)
.show();
}
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(holder);
int rotation = ((Activity) m_context).getWindowManager()
.getDefaultDisplay().getRotation();
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) {
// Log.i(TAG, "0");
mCamera.setDisplayOrientation(90);
} else if (rotation == Surface.ROTATION_90) {
// Log.i(TAG, "90");
mCamera.setDisplayOrientation(0);
} else if (rotation == Surface.ROTATION_270) {
// Log.i(TAG, "270");
mCamera.setDisplayOrientation(180);
}
} catch (IOException exception) {
mCamera.release();
mCamera = null;
// TODO: add more exception handling logic here
}
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public void setCameraFacingInfo(int cameraFacingInfo) {
mCameraFacingInfo = cameraFacingInfo;
}
}
Try to change your jpegCallback class to this:
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//Creating empty file in sdcard
File pictureFile = new File(String.format("/sdcard/Demo%d.jpg", System.currentTimeMillis()));
if (pictureFile == null) {
Log.e("IMAGE CAPTURE", "Error creating media file, check storage permissions: ");
return;
}
if (data != null) {
BitmapFactory.Options opts = new BitmapFactory.Options();
ActivityManager activityManager = (ActivityManager) MainActivity.this.getSystemService(Activity.ACTIVITY_SERVICE);
int memoryLimit = 100;
if (activityManager != null) {
memoryLimit = activityManager.getMemoryClass();
}
// Considering memory limitation of device we will resize image to prevent OutOfMemory
if (memoryLimit < 20) {
opts.inSampleSize = 6;
} else if (memoryLimit < 40) {
opts.inSampleSize = 4;
} else if (memoryLimit < 64) {
opts.inSampleSize = 2;
}
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
fos.close();
}
bitmap.recycle();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
}

Can't take picture in android

I'm trying to take a picture in Android using the code below. The current code doesn't work, namely i cant find the picture inside my phone's storage.
public class CameraShooting implements SurfaceHolder.Callback {
Context context;
Camera camera;
CameraInfo camerainfo;
Camera.Parameters paras;
SurfaceView surfaceview;
SurfaceHolder surfaceholder;
PictureCallback picturecallback;
SurfaceHolder.Callback callback = (SurfaceHolder.Callback) this;
public CameraShooting(Context context) {
this.context = context;
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
surfaceview = new SurfaceView(context);
surfaceholder = surfaceview.getHolder();
surfaceholder.addCallback(callback);
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
int numbersofCamera = camera.getNumberOfCameras();
camerainfo = new CameraInfo();
/*
* for(int i =0; i < numbersofCamera; i++){ Camera.getCameraInfo(i,
* camerainfo); if (camerainfo.facing ==
* CameraInfo.CAMERA_FACING_FRONT){ camera.open(i); }}
*/
camera.open(0);
try {
camera.setPreviewDisplay(surfaceholder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
camera.takePicture(null, null, mPicture);
Toast.makeText(context, "Picture taken", Toast.LENGTH_SHORT).show();
};
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS
), "picture taken");
try {
OutputStream fos = new BufferedOutputStream(new FileOutputStream(pictureFile));
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
};
};
}
Note, I already included
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try:
fos.flush();
before you close the OutputStream.

Rotating picture taken by Camera in Android

I am trying to do an application that takes a picture with the front facing camera without a UI and i have been successful doing that but the only problem is the picture is always taken in landscape mode, is there any ways to force it to portrait mode?
public class TakePicture extends Activity implements SurfaceHolder.Callback
{
private ImageView iv_image;
private SurfaceView sv;
private Bitmap bmp;
private SurfaceHolder sHolder;
private Camera mCamera;
private int cameraId = 1;
private Parameters parameters;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv_image = (ImageView) findViewById(R.id.imageView);
sv = (SurfaceView) findViewById(R.id.surfaceView);
sHolder = sv.getHolder();
sHolder.addCallback(this);
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
parameters = mCamera.getParameters();
mCamera.setParameters(parameters);
mCamera.startPreview();
//mCamera.setDisplayOrientation(90);
//sets what code should be executed after the picture is taken
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d("DEBUG", "Can't create directory to save image.");
Toast.makeText(TakePicture.this, "Can't create directory to save image.",
Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date + ".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(TakePicture.this, "New Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
finish();
} catch (Exception error) {
Log.d("DEBUG", "File" + filename + "not saved: "
+ error.getMessage());
Toast.makeText(TakePicture.this, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
}
};
mCamera.takePicture(null, null, mCall);
}
public void surfaceCreated(SurfaceHolder holder)
{
// The Surface has been created, acquire the camera and tell it where
// to draw the preview.
//mCamera = Camera.open();
mCamera = Camera.open(cameraId);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
public void surfaceDestroyed(SurfaceHolder holder)
{
//stop the preview
mCamera.stopPreview();
//release the camera
mCamera.release();
//unbind the camera from this object
mCamera = null;
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "Camera!");
}
}
As far as I remember when trying to do this, it was a bit tricky.
One approach I found was:
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
Parameters params = mCamera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
params.set("orientation", "portrait");
try {
//not sure if this block of code had an OR relationship with the previous line params.set("orientation", "portrait");
Method rotateSet = Camera.Parameters.class.getMethod("setRotation", new Class[] { Integer.TYPE });
Object arguments[] = new Object[] { new Integer(90) };
rotateSet.invoke(params, arguments);
} catch (Exception e) {
e.printStackTrace();
}
}
mCamera.setParameters(params);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
But it didn't work for me (althought I was using Android version higher than 2.0, where this was supposed to work).
I also found a hack using reflection, and that worked:
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {}
setDisplayOrientation(mCamera, 90);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
Where setDisplayOrientation is:
protected void setDisplayOrientation(Camera camera, int angle){
Method setDisplayOrientationMethod;
try {
setDisplayOrientationMethod = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
if (setDisplayOrientationMethod != null) {
setDisplayOrientationMethod.invoke(camera, new Object[] {angle});
}
} catch (Exception e1) {}
}

Categories

Resources