Rename image name to datetime stamp - android

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

Related

Captured Image Storage in SDCard captured using Camera(Not Intent)

I Created a app that captures image and stores in the SD Card. The app seems to work fine with the previewing. But the problem is that when I run the app on my phone through eclipse the image gets captured. If I run my app in a normal way and try to capture the image, the image doesn't get captured.
I have attached my code below
My MainActivity.class
public class MainActivity extends Activity {
private ImageHandler preview;
Camera camera;
int cameraID, currentCamera;
Button capture;
FrameLayout imageLayout;
SurfaceView imgl;
private static final String TAG = "CallCamera";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* Invoking Camera and Setting the ImageHandler for preview
*/
camera = getCameraInstance();
preview = new ImageHandler(this, camera);
/*
* Getting the ID of the FrameLayout that displays the camera
*/
imageLayout = (FrameLayout) findViewById(R.id.preview_layout);
imageLayout.addView(preview);
/*
* Getting the ID of capture Button and setting its Functionality
*/
capture = (Button) findViewById(R.id.cameraButton);
capture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(null, null, null, pic);
}
});
}
private Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera cam = null;
try {
cam = Camera.open();
} catch (Exception e) {
}
return cam;
}
PictureCallback pic = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
// File picFile = getOutputPhotoFile();
// if(picFile == null){
// return;
// }
//
// try{
// FileOutputStream fos = new FileOutputStream(picFile);
// fos.write(data);
// fos.close();
//
// }catch(FileNotFoundException e){
//
// }catch (IOException e){
//
// }
//
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d(TAG, "Can't create directory to save image.");
Toast.makeText(getApplicationContext(),
"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(getApplicationContext(),
"New Image saved:" + photoFile, Toast.LENGTH_LONG)
.show();
} catch (Exception error) {
Log.d(TAG,
"File" + filename + "not saved: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Image could not be saved.", Toast.LENGTH_LONG).show();
}
camera.startPreview();
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "CameraAPIDemo");
}
};
// private File getOutputPhotoFile() {
//
// File directory = new File(
// Environment
// .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
// "IMAGES_CAMERA");
//
// if (!directory.exists()) {
// if (!directory.mkdirs()) {
// Log.e(TAG, "Failed to create storage directory.");
// return null;
// }
// }
//
// String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss")
// .format(new Date());
//
// return new File(directory.getPath() + File.separator + "IMG_"
// + timeStamp + ".jpg");
// }
//
#Override
public void onResume() {
super.onResume();
if (camera == null) {
camera = Camera.open();
preview.setCamera(camera);
}
}
}
My Preview/ ImageHandler.class
public class ImageHandler extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder holder;
private Camera imgCamera;
List<Size> imgSupportedPreviewSizes;
public ImageHandler(Context context, Camera camera) {
super(context);
// TODO Auto-generated constructor stub
this.imgCamera = camera;
this.holder = this.getHolder();
this.holder.addCallback(this);
this.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
try {
imgCamera.setPreviewDisplay(holder);
imgCamera.startPreview();
} catch (IOException e) {
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
imgCamera.setPreviewDisplay(holder);
imgCamera.startPreview();
imgCamera.setDisplayOrientation(90);
} catch (Exception e) {
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
imgCamera.stopPreview();
imgCamera.release();
}
public void setCamera(Camera camera) {
imgCamera = camera;
if (imgCamera != null) {
imgSupportedPreviewSizes = imgCamera.getParameters()
.getSupportedPreviewSizes();
requestLayout();
}
}
}
I want to be able to capture image when I run the app normally through my phone.

Taking more than one shots with Android programmatically?

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

Camera Orientation is not Proper in android

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.

Android Save Image to SD Card

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" />

Android Closing the camera correctly

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

Categories

Resources