I need to use camera without preview and take more than one shots.
I have written my code and I am able to take one shot, it works properly.
But I could not handle to do more than once. Because the logic of Camera Service i tried a method CreateCameraTakeShot, still no success.
Could you please help me with that?
Here is my code;
public class ContinuingCallActivity extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
FileOutputStream outStream;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_continuingcall);
//getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// for(int i=0;i<10;i++)
//{
mHandler.postDelayed(mLaunchTask, 1000);
//}
}
Handler mHandler = new Handler();
private Runnable mLaunchTask = new Runnable() {
#Override
public void run() {
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
//createCameraTakeShot();
}
};
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/MySight/";
File newdir = new File(dir);
newdir.mkdirs();
Date d = new Date();
CharSequence dateOfShot = DateFormat.format("dd-MM-yy hh:mm:ss", d.getTime());
String file = dir+dateOfShot+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
outStream = new FileOutputStream(newfile);
outStream.write(bytes.toByteArray());
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + arg0.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public void createCameraTakeShot()
{
camera = Camera.open();
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
camera.stopPreview();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
//camera.release();
//camera = null;
previewing = false;
}
}
you can use timer task insted of handler to take picture prodically
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, 1000, 1000);
}
class MyTimerTask extends TimerTask {
public void run() {
// ERROR
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
}
}
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/MySight/";
File newdir = new File(dir);
newdir.mkdirs();
Date d = new Date();
CharSequence dateOfShot = DateFormat.format("dd-MM-yy hh:mm:ss", d.getTime());
String file = dir+dateOfShot+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
outStream = new FileOutputStream(newfile);
outStream.write(bytes.toByteArray());
outStream.close();
Log.d("Log", "onPictureTaken - wrote bytes: " + arg0.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
public void createCameraTakeShot()
{
camera = Camera.open();
if (camera != null)
{
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
camera.takePicture(null,myPictureCallback_RAW, myPictureCallback_JPG);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
//camera.release();
//camera = null;
previewing = false;
}
}
Related
How do i change the codes so that the image's name will be save as date time stamp?
Button buttonTakePicture;
final int RESULT_SAVEIMAGE = 0;
/** Called when the activity is first created. */ #Override public
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_layout);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFormat(PixelFormat.UNKNOWN); surfaceView =
(SurfaceView) findViewById(R.id.camerapreview); surfaceHolder =
surfaceView.getHolder(); surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext()); View
viewControl = controlInflater.inflate(R.layout.camera_control, null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); this.addContentView(viewControl, layoutParamsControl);
buttonTakePicture = (Button) findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG); } });
LinearLayout layoutBackground = (LinearLayout)
findViewById(R.id.background);
layoutBackground.setOnClickListener(new
LinearLayout.OnClickListener() { public void onClick(View arg0) {
// TODO Auto-generated method stub
buttonTakePicture.setEnabled(false);
camera.autoFocus(myAutoFocusCallback); } }); }
AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback() {
public void onAutoFocus(boolean arg0, Camera arg1) { // TODO
Auto-generated method stub buttonTakePicture.setEnabled(true); }
};
ShutterCallback myShutterCallback = new ShutterCallback() { public
void onShutter() { // TODO Auto-generated method stub
} };
PictureCallback myPictureCallback_RAW = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) { // TODO
Auto-generated method stub
} };
PictureCallback myPictureCallback_JPG = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) { // TODO
Auto-generated method stub /*
* Bitmap bitmapPicture = BitmapFactory.decodeByteArray(arg0, 0,
* arg0.length);
*/
Uri uriTarget = getContentResolver().insert(
Media.EXTERNAL_CONTENT_URI, new ContentValues()); OutputStream imageFileOS; try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(CameraActivity.this,"Image saved: " + uriTarget.toString(),Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace(); } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); } camera.startPreview(); } };
public void surfaceChanged(SurfaceHolder holder, int format, int
width,int height) { // TODO Auto-generated method stub if
(previewing) { camera.stopPreview(); previewing = false; }
if (camera != null) { try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true; } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); } } }
public void surfaceCreated(SurfaceHolder holder) { // TODO
Auto-generated method stub camera = Camera.open(); }
public void surfaceDestroyed(SurfaceHolder holder) { // TODO
Auto-generated method stub camera.stopPreview(); camera.release();
camera = null; previewing = false; } }
I think you could use Content Resolver to achieve it,
ContentValues v = new ContentValues();
v.put(Images.Media.TITLE, title);
v.put(Images.Media.DISPLAY_NAME, System..currenttimemillis());
v.put(Images.Media.DESCRIPTION, description);
v.put(Images.Media.DATE_ADDED, dateTaken);
v.put(Images.Media.DATE_TAKEN, dateTaken);
v.put(Images.Media.DATE_MODIFIED, dateTaken) ;
v.put(Images.Media.MIME_TYPE, “image/jpeg”);
v.put(Images.Media.ORIENTATION, orientation);
Give it a try.
This might help
private void SaveImage(Bitmap finalBitmap, String retailerArray2) {
long timeStamp = Calendar.getInstance().getTimeInMillis();
String dateStamp = DateHelper.dateTime(timeStamp,
"dd-MM-yyyy HH:mm[:ss]");
File myDirectory = new File(root + "/ Gallery/" );
if (!myDirectory.exists()) {
myDirectory.mkdirs();
}
String fname = Name + " -- " + dateStamp + ".jpg";
File file = new File(myDirectory, fname);
}
I want to take a picture with my phone via an application and save the image on my phone.
I've tried many of the solutions proposed on the stackoverflow questions but it did not mark so I built a method that saves the file with the right name ... but the file is empty (0kb)!
Here is my code
public class GameActivity extends Activity implements SurfaceHolder.Callback/*,Camera.PictureCallback*/ {
private Camera camera;
private SurfaceView surfaceCamera;
public Handler handler = new Handler();
private boolean isPreview=false;
private SurfaceHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameactivity);
surfaceCamera = (SurfaceView) findViewById(R.id.surfaceViewCamera);
getWindow().setFormat(PixelFormat.UNKNOWN);
holder = surfaceCamera.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
ImageView image = (ImageView) findViewById(R.id.imageView3);
image.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);
return false;
}
Camera.ShutterCallback myShutterCallback = new Camera.ShutterCallback() {
public void onShutter() {
// TODO bl
}
};
PictureCallback myPictureCallback_RAW = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}
};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "/KersplattFolder");
imagesFolder.mkdirs();
String fileName = "image.jpg";
File output = new File(imagesFolder, fileName);
try {
FileOutputStream fos = new FileOutputStream(output);
fos.write(data[0]);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(GameActivity.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
camera.startPreview();
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (isPreview) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(width,height);
camera.setParameters(p);
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
isPreview=true;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
isPreview=false;
camera.release();
}
EDIT1 : when I put data instead of data[0] I save a black image as well but the file has a weight so I guess the real image is somewhere...
EDIT2
I have added the code
File output = new File(imagesFolder, fileName);
Uri outputFileUri = Uri.fromFile(output);
String filePath = outputFileUri.getPath();
File file= new File(filePath);
try {
FileOutputStream fos = new FileOutputStream(file,true);
fos.write(data);
fos.close();
}
Still have the black image
have you defined the required permissions in your Android manifest like described here?
<manifest ... >
<uses-feature android:name="android.hardware.camera" />
...
</manifest ... >
UPDATE:
Ok, remove the brackets after data: data instead of data[]. Then it should work.
Your code: fos.write(data[0]); is wrong. I am surprised that you did not get an exception
Here is the code I used to save the byte array after taking a picture. "data" is the byte array.
String filePath = outputFileUri.getPath(); // .getEncodedPath();
File file = new File(filePath);
FileOutputStream os;
try {
os = new FileOutputStream(file, true);
os.write(data);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am using custom camera and surface view for capturing image but the problem is the camera orientation is not proper, following is my code and sorry for my bad English communication.
public class Camera_Activity extends Activity implements
SurfaceHolder.Callback {
private Camera camera = null;
private SurfaceView cameraSurfaceView = null;
private SurfaceHolder cameraSurfaceHolder = null;
private boolean previewing = false;
private Display display = null;
private static int wid = 0, hgt = 0;
private LayoutInflater layoutInflater = null;
private View cameraViewControl = null;
private LayoutParams layoutParamsControl = null;
private Button btnCapture = null;
ImageView mImgView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
display = getWindowManager().getDefaultDisplay();
wid = display.getWidth();
hgt = display.getHeight();
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.camera);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
mImgView1.setImageResource(R.drawable.first_leg);
cameraSurfaceView = (SurfaceView) findViewById(R.id.cameraSurfaceView);
cameraSurfaceHolder = cameraSurfaceView.getHolder();
cameraSurfaceHolder.addCallback(this);
cameraSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
layoutInflater = LayoutInflater.from(getBaseContext());
layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
cameraViewControl = layoutInflater.inflate(R.layout.cambutton, null);
this.addContentView(cameraViewControl, layoutParamsControl);
cameraViewControl = layoutInflater.inflate(R.layout.vampireimage, null);
this.addContentView(cameraViewControl, layoutParamsControl);
btnCapture = (Button) findViewById(R.id.btnCapture);
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.takePicture(cameraShutterCallback,
cameraPictureCallbackRaw, cameraPictureCallbackJpeg);
}
});
}
ShutterCallback cameraShutterCallback = new ShutterCallback() {
#Override
public void onShutter() {
// TODO Auto-generated method stub
System.out.println("Hello Shutter");
}
};
PictureCallback cameraPictureCallbackRaw = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
System.out.println("Hello Picture");
}
};
PictureCallback cameraPictureCallbackJpeg = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
Bitmap cameraBitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
wid = cameraBitmap.getWidth();
hgt = cameraBitmap.getHeight();
Bitmap newImage = Bitmap.createBitmap(wid, hgt,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newImage);
canvas.drawBitmap(cameraBitmap, 0f, 0f, null);
Constants.mImageBitmap.clear();
Constants.mImageBitmap.add(cameraBitmap);
File storagePath = new File(
Environment.getExternalStorageDirectory() + "/Photos/");
storagePath.mkdirs();
File myImage = new File(storagePath, "1.jpg");
try {
FileOutputStream out = new FileOutputStream(myImage);
newImage.compress(Bitmap.CompressFormat.JPEG, 80, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
Log.d("In Saving File", e + "");
} catch (IOException e) {
Log.d("In Saving File", e + "");
}
camera.startPreview();
newImage.recycle();
newImage = null;
// cameraBitmap.recycle();
// cameraBitmap = null;
Intent mInPreview = new Intent(Camera_Activity.this,
Preview_Activity.class);
mInPreview.putExtra("Value", "First");
startActivity(mInPreview);
finish();
}
};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
System.out.println("Hello 2");
}
try {
Camera.Parameters parameters = camera.getParameters();
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
.getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
parameters.setPreviewSize(height, width);
camera.setDisplayOrientation(90);
}
if (display.getRotation() == Surface.ROTATION_90) {
parameters.setPreviewSize(width, height);
}
if (display.getRotation() == Surface.ROTATION_180) {
parameters.setPreviewSize(height, width);
}
if (display.getRotation() == Surface.ROTATION_270) {
parameters.setPreviewSize(width, height);
camera.setDisplayOrientation(180);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(cameraSurfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
camera = Camera.open();
} catch (RuntimeException e) {
Toast.makeText(
getApplicationContext(),
"Device camera is not working properly, please try after sometime.",
Toast.LENGTH_LONG).show();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("Hello 3");
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("3DSoles");
alert.setMessage("Do U Want to Exit?");
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("3DSoles");
alert.setMessage("Do U Want to Exit?");
alert.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
}
return super.onKeyDown(keyCode, event);
}
}
Camera class is not expected to support setPreview(height, width)
see http://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation%28int%29 for the official way to choose Camera.setDisplayOrientation()
Starting from API 14 (ICS and higher), camera is expected to support setDisplayOrientation() without
interrupting preview.
For older platforms, I would recommend to disable change of orientation while the camera preview is active; reset of camera (stopPreview() + startPreview) may take too long for UX to be freiendly. Often, preview activities either work with fixed orientation or "simulate" in software orientation change in response to accelerometer events.
UPDATE
Added
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
to the manifest all works ok now.
Ok so I have a app I have started to create which in the end I want to be able to take a picture, which then takes you to another screen which lets you be able to "Use" or "Retake" the picture.
When the image is took it needs to be saved into a new folder on the SD Card, (if the folder is not there then it needs to create it). I had all this working a couple of weeks ago but after i did some editing and shut down eclipse I cant seem to get it back working?
The section for this is after int imageNum = 0; i have added imagesFolder.mkdirs(); which i belive is correct to create a new folder but even this seems not to be working now.
Now the image just gets took and neither the new folder gets created or the image gets saved.
public class AndroidCamera extends Activity implements SurfaceHolder.Callback {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
final int RESULT_SAVEIMAGE = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
Button buttonTakePicture = (Button) findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW,
myPictureCallback_JPG);
}
});
}
ShutterCallback myShutterCallback = new ShutterCallback() {
public void onShutter() {
// TODO Auto-generated method stub
}
};
PictureCallback myPictureCallback_RAW = new PictureCallback() {
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}
};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
int imageNum = 0;
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "BeatEmUp");
imagesFolder.mkdirs();
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved: ",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
}};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
You should make sure the manifest lists the permission to write to the SD card:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ok this has been happening to me a few times over the past few weeks and I can't figure out how to fix it. Basically my app uses the camera but every so often after a few goes with the camera on the app it then force closes sometimes and cannot be used even with other apps or the default camera on the phone.
I found the only way to fix this is to restart the phone.
From what I have read so far I understand I need to call
camera.release();
camera = null;
But I still get the error of force close sometimes, is it possible for someone just to take a look through maybe I am missing a camera.release(); somewhere.
public class AndroidCamera extends Activity implements SurfaceHolder.Callback{
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
final int RESULT_SAVEIMAGE = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
}});
}
ShutterCallback myShutterCallback = new ShutterCallback(){
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
int imageNum = 0;
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Punch");
imagesFolder.mkdirs(); // <----
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getBaseContext(), Punch.class);
intent.putExtra("filepath",uriSavedImage.toString());
//just using a request code of zero
int request=0;
startActivityForResult(intent,request);
}};
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
camera.release();
e.printStackTrace();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
try {
Camera.Parameters parameters = camera.getParameters();
if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
// This is an undocumented although widely known feature
parameters.set("orientation", "portrait");
// For Android 2.2 and above
camera.setDisplayOrientation(90);
// Uncomment for Android 2.0 and above
parameters.setRotation(90);
} else {
// This is an undocumented although widely known feature
parameters.set("orientation", "landscape");
// For Android 2.2 and above
camera.setDisplayOrientation(0);
// Uncomment for Android 2.0 and above
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
} catch (IOException exception) {
camera.release();
}
camera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
if(previewing && camera != null) {
if(camera!=null) {
camera.stopPreview();
camera.release();
camera = null;
}
previewing = false;
}
}
}
The logcat gave me (there is more but I think its because the camera force closes on me so the rest of the app doesn't run.
01-03 14:59:17.835: D/AndroidRuntime(16531): Shutting down VM
01-03 14:59:17.835: W/dalvikvm(16531): threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)
01-03 14:59:17.845: E/AndroidRuntime(16531): FATAL EXCEPTION: main
01-03 14:59:17.845: E/AndroidRuntime(16531): java.lang.RuntimeException: Fail to connect to camera service
I solved the same problem with closing camera in onPause() event
#Override
protected void onPause()
{
super.onPause();
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}