Can't take picture in android - 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.

Related

Custom camera new captured image overwrites the old one

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

Android Front Camera image is not being saved properly

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

Tried capturing multiple photos in Android but didn't work

I'm a newbie in Android and I've been trying to make an Android camera application that is supposed to be able to capture 5 images when we click the camera button. But the code I'm working on doesn't seem to work. Is there anyone that can help please? So far, this is the code:
public class CameraDemo extends Activity {
private static final String TAG = "CameraDemo";
Camera camera;
Preview preview;
Button buttonClick;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preview = new Preview(this);
((FrameLayout) findViewById(R.id.preview)).addView(preview);
buttonClick = (Button) findViewById(R.id.buttonClick);
buttonClick.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
int count = 0;
while(count < 5){
preview.camera.takePicture(shutterCallback, rawCallback, jpegCallback);
count++;
try {
wait(1000);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
}
});
Log.d(TAG, "onCreate'd");
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
// write to local sandbox file system
// outStream = CameraDemo.this.openFileOutput(String.format("%d.jpg", System.currentTimeMillis()), 0);
// Or write to sdcard
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Log.d(TAG, "onPictureTaken - jpeg");
}
};
}
And this is the other class named Preview:
class Preview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "Preview";
SurfaceHolder mHolder;
public Camera camera;
Preview(Context context) {
super(context);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, acquire the camera and tell it where
// to draw.
camera = Camera.open();
try {
camera.setPreviewDisplay(holder);
camera.setPreviewCallback(new PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
Log.d(TAG, "onPreviewFrame - wrote bytes: " + data.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Preview.this.invalidate();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return, so stop the preview.
// Because the CameraDevice object is not a shared resource, it's very
// important to release it when the activity is paused.
camera.stopPreview();
camera = null;
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(w, h);
camera.setParameters(parameters);
camera.startPreview();
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
Paint p= new Paint(Color.RED);
Log.d(TAG,"draw");
canvas.drawText("PREVIEW", canvas.getWidth()/2, canvas.getHeight()/2, p );
}
}

Android Camera Take Picture and SAVE or send to next activity

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

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