I am creating small app which previews camera and when clicking on screen saves image.
My problem is when image is saved, I want to start different activity which will do preview and have some tools on it. But what ever I do activity doesn't start.
Here is my code
public class CameraActivity extends Activity {
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
private boolean cameraConfigured = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
preview = (SurfaceView) findViewById(R.id.preview);
Button button = (Button) findViewById(R.id.button_capture);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (camera != null) {
camera.takePicture(null, null, photoCallback);
onPause();
Intent intent = new Intent(CameraActivity.this, PreviewAndSaveActivity.class);
intent.putExtra("image", "");
CameraActivity.this.startActivity(intent);
}
}
});
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
Camera.CameraInfo info = new Camera.CameraInfo();
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
camera = Camera.open(i);
}
}
}
if (camera == null) {
camera = Camera.open();
}
startPreview();
}
#Override
public void onPause() {
if (camera != null) {
if (inPreview) {
camera.stopPreview();
}
camera.release();
camera = null;
}
inPreview = false;
super.onPause();
}
private Camera.Size getBestPreviewSize(int width, int height,
Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
}
return (result);
}
private Camera.Size getSmallestPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea < resultArea) {
result = size;
}
}
}
return (result);
}
private void initPreview(int width, int height) {
if (camera != null && previewHolder.getSurface() != null) {
try {
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
Toast.makeText(CameraActivity.this, t.getMessage(),
Toast.LENGTH_LONG).show();
}
if (!cameraConfigured) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height, parameters);
Camera.Size pictureSize = getSmallestPictureSize(parameters);
if (size != null && pictureSize != null) {
parameters.setPreviewSize(size.width, size.height);
parameters.setPictureSize(pictureSize.width,
pictureSize.height);
parameters.setPictureFormat(ImageFormat.JPEG);
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
camera.setParameters(parameters);
cameraConfigured = true;
}
}
}
}
private void startPreview() {
if (cameraConfigured && camera != null) {
camera.startPreview();
inPreview = true;
}
}
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
// no-op -- wait until surfaceChanged()
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
initPreview(width, height);
startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
};
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
camera.takePicture(null, null, new PhotoHandler(
getApplicationContext()));
camera.startPreview();
inPreview = true;
}
};
}
And in PhotoHandler after decoding and saving image I want to start activity
public class PhotoHandler implements PictureCallback {
private final Context context;
public PhotoHandler(Context context) {
this.context = context;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d("", "Can't create directory to save image.");
Toast.makeText(context, "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 = "pic_" + date + ".jpg";
String pictureName = pictureFileDir.getPath() + File.separator
+ photoFile;
File pictureFile = new File(pictureName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pictureFile);
fos.write(data);
Intent intent = new Intent(context, PreviewAndSaveActivity.class);
intent.putExtra("image", pictureName);
context.startActivity(intent);
} catch (Exception error) {
Toast.makeText(context, "Image could not be saved.",
Toast.LENGTH_LONG).show();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
}
}
}
}
private File getDir() {
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "dir");
}
}
Any suggestion what am I doing wrong?
try this code :
(Replace your button click listener )
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (camera != null) {
camera.takePicture(null, null, photoCallback);
onPause();
Intent intent = new Intent(CameraActivity.this, PreviewAndSaveActivity.class);
intent.putExtra("image", "");
CameraActivity.this.startActivityForResult(intent, 100);
}
}
});
In your CameraActivity add this callback method to redirect on another activity after image save :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
// start you new activity from here...
}
super.onActivityResult(requestCode, resultCode, data);
}
Related
Hi aim working n android application to detect page number using camera preview.
After i received frame from OnPreviewFrame i'm doing real time image processing using opencv to find page number position .Now my question is How can i draw rectangle on surface View ?
Use this code
PreviewDemo.java
public class PreviewDemo extends Activity implements OnClickListener {
private SurfaceView preview = null;
private SurfaceHolder previewHolder = null;
private Camera camera = null;
private boolean inPreview = false;
ImageView image;
Bitmap bmp, itembmp;
static Bitmap mutableBitmap;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
File imageFileName = null;
File imageFileFolder = null;
private MediaScannerConnection msConn;
Display d;
int screenhgt, screenwdh;
ProgressDialog dialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview);
image = (ImageView) findViewById(R.id.image);
preview = (SurfaceView) findViewById(R.id.surface);
previewHolder = preview.getHolder();
previewHolder.addCallback(surfaceCallback);
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
previewHolder.setFixedSize(getWindow().getWindowManager()
.getDefaultDisplay().getWidth(), getWindow().getWindowManager()
.getDefaultDisplay().getHeight());
}
#Override
public void onResume() {
super.onResume();
camera = Camera.open();
}
#Override
public void onPause() {
if (inPreview) {
camera.stopPreview();
}
camera.release();
camera = null;
inPreview = false;
super.onPause();
}
private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size: parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
}
return (result);
}
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(previewHolder);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
Toast.makeText(PreviewDemo.this, t.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width,
int height) {
Camera.Parameters parameters = camera.getParameters();
Camera.Size size = getBestPreviewSize(width, height,
parameters);
if (size != null) {
parameters.setPreviewSize(size.width, size.height);
camera.setParameters(parameters);
camera.startPreview();
inPreview = true;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
};
Camera.PictureCallback photoCallback = new Camera.PictureCallback() {
public void onPictureTaken(final byte[] data, final Camera camera) {
dialog = ProgressDialog.show(PreviewDemo.this, "", "Saving Photo");
new Thread() {
public void run() {
try {
Thread.sleep(1000);
} catch (Exception ex) {}
onPictureTake(data, camera);
}
}.start();
}
};
public void onPictureTake(byte[] data, Camera camera) {
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
mutableBitmap = bmp.copy(Bitmap.Config.ARGB_8888, true);
savePhoto(mutableBitmap);
dialog.dismiss();
}
class SavePhotoTask extends AsyncTask < byte[], String, String > {#Override
protected String doInBackground(byte[]...jpeg) {
File photo = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return (null);
}
}
public void savePhoto(Bitmap bmp) {
imageFileFolder = new File(Environment.getExternalStorageDirectory(), "Rotate");
imageFileFolder.mkdir();
FileOutputStream out = null;
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH)) + fromInt(c.get(Calendar.DAY_OF_MONTH)) + fromInt(c.get(Calendar.YEAR)) + fromInt(c.get(Calendar.HOUR_OF_DAY)) + fromInt(c.get(Calendar.MINUTE)) + fromInt(c.get(Calendar.SECOND));
imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
scanPhoto(imageFileName.toString());
out = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public String fromInt(int val) {
return String.valueOf(val);
}
public void scanPhoto(final String imageFileName) {
msConn = new MediaScannerConnection(PreviewDemo.this, new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msConn.scanFile(imageFileName, null);
Log.i("msClient obj in Photo Utility", "connection established");
}
public void onScanCompleted(String path, Uri uri) {
msConn.disconnect();
Log.i("msClient obj in Photo Utility", "scan completed");
}
});
msConn.connect();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
onBack();
}
return super.onKeyDown(keyCode, event);
}
public void onBack() {
Log.e("onBack :", "yes");
camera.takePicture(null, null, photoCallback);
inPreview = false;
}
#Override
public void onClick(View v) {
}
}
Preview.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<android.view.SurfaceView
android:id="#+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Add the Permissions also
I have an android app which consists of a Button.
When you click on Button, an image should be captured from the camera without opening the camera application (the image should be captured in background).
How to implement this feature?
Any suggestions will be of great help.
Thanks a lot in advance.
Here is my whole working project of How to capture image in background without SurfaceView.
// You can start your service to capturing image wherever you want not should from activity.
also need to ask need permission in your Activity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, APP_PERMISSION_REQUEST);
}
handle intent in click or where you needed
Intent front_translucent = new Intent(getApplication()
.getApplicationContext(), CameraService.class);
front_translucent.putExtra("Front_Request", true);
front_translucent.putExtra("Quality_Mode",
camCapture.getQuality());
getApplication().getApplicationContext().startService(
front_translucent);
public class CamerService extends Service implements
SurfaceHolder.Callback {
// Camera variables
// a surface holder
// a variable to control the camera
private Camera mCamera;
// the camera parameters
private Parameters parameters;
private Bitmap bmp;
FileOutputStream fo;
private String FLASH_MODE;
private int QUALITY_MODE = 0;
private boolean isFrontCamRequest = false;
private Camera.Size pictureSize;
SurfaceView sv;
private SurfaceHolder sHolder;
private WindowManager windowManager;
WindowManager.LayoutParams params;
public Intent cameraIntent;
SharedPreferences pref;
Editor editor;
int width = 0, height = 0;
/** Called when the activity is first created. */
#Override
public void onCreate() {
super.onCreate();
}
private Camera openFrontFacingCameraGingerbread() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
int cameraCount = 0;
Camera cam = 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 {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e("Camera",
"Camera failed to open: " + e.getLocalizedMessage());
/*
* Toast.makeText(getApplicationContext(),
* "Front Camera failed to open", Toast.LENGTH_LONG)
* .show();
*/
}
}
}
return cam;
}
private void setBesttPictureResolution() {
// get biggest picture size
width = pref.getInt("Picture_Width", 0);
height = pref.getInt("Picture_height", 0);
if (width == 0 | height == 0) {
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// save width and height in sharedprefrences
width = pictureSize.width;
height = pictureSize.height;
editor.putInt("Picture_Width", width);
editor.putInt("Picture_height", height);
editor.commit();
} else {
// if (pictureSize != null)
parameters.setPictureSize(width, height);
}
}
private Camera.Size getBiggesttPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
return (result);
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** Check if this device has front camera */
private boolean checkFrontCamera(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FRONT)) {
// this device has front camera
return true;
} else {
// no front camera on this device
return false;
}
}
Handler handler = new Handler();
private class TakeImage extends AsyncTask<Intent, Void, Void> {
#Override
protected Void doInBackground(Intent... params) {
takeImage(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
private synchronized void takeImage(Intent intent) {
if (checkCameraHardware(getApplicationContext())) {
Bundle extras = intent.getExtras();
if (extras != null) {
String flash_mode = extras.getString("FLASH");
FLASH_MODE = flash_mode;
boolean front_cam_req = extras.getBoolean("Front_Request");
isFrontCamRequest = front_cam_req;
int quality_mode = extras.getInt("Quality_Mode");
QUALITY_MODE = quality_mode;
}
if (isFrontCamRequest) {
// set flash 0ff
FLASH_MODE = "off";
// only for gingerbread and newer versions
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(sv.getHolder());
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
Camera.Parameters parameters = mCamera.getParameters();
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
// return 4;
} else {
mCamera = null;
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Your Device dosen't have Front Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
/*
* sHolder = sv.getHolder(); // tells Android that this
* surface will have its data // constantly // replaced if
* (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
*/
} else {
if (checkFrontCamera(getApplicationContext())) {
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(sv.getHolder());
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
Camera.Parameters parameters = mCamera.getParameters();
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
// return 4;
} else {
mCamera = null;
/*
* Toast.makeText(getApplicationContext(),
* "API dosen't support front camera",
* Toast.LENGTH_LONG).show();
*/
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Your Device dosen't have Front Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
// Get a surface
/*
* sHolder = sv.getHolder(); // tells Android that this
* surface will have its data // constantly // replaced
* if (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS
* );
*/
}
}
} else {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = Camera.open();
} else
mCamera = getCameraInstance();
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
if (FLASH_MODE == null || FLASH_MODE.isEmpty()) {
FLASH_MODE = "auto";
}
parameters.setFlashMode(FLASH_MODE);
// set biggest picture
setBesttPictureResolution();
// log quality and image format
Log.d("Qaulity", parameters.getJpegQuality() + "");
Log.d("Format", parameters.getPictureFormat() + "");
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
Log.d("ImageTakin", "OnTake()");
mCamera.takePicture(null, null, mCall);
} else {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Camera is unavailable !",
Toast.LENGTH_LONG).show();
}
});
}
// return 4;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TAG", "CmaraHeadService()::takePicture", e);
}
// Get a surface
/*
* sHolder = sv.getHolder(); // tells Android that this surface
* will have its data constantly // replaced if
* (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
*/
}
} else {
// display in long period of time
/*
* Toast.makeText(getApplicationContext(),
* "Your Device dosen't have a Camera !", Toast.LENGTH_LONG)
* .show();
*/
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Your Device dosen't have a Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
// return super.onStartCommand(intent, flags, startId);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// sv = new SurfaceView(getApplicationContext());
cameraIntent = intent;
Log.d("ImageTakin", "StartCommand()");
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.width = 1;
params.height = 1;
params.x = 0;
params.y = 0;
sv = new SurfaceView(getApplicationContext());
windowManager.addView(sv, params);
sHolder = sv.getHolder();
sHolder.addCallback(this);
// tells Android that this surface will have its data constantly
// replaced
if (Build.VERSION.SDK_INT < 11)
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
return 1;
}
Camera.PictureCallback mCall = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
Log.d("ImageTakin", "Done");
if (bmp != null)
bmp.recycle();
System.gc();
bmp = decodeBitmap(data);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (bmp != null && QUALITY_MODE == 0)
bmp.compress(Bitmap.CompressFormat.JPEG, 70, bytes);
else if (bmp != null && QUALITY_MODE != 0)
bmp.compress(Bitmap.CompressFormat.JPEG, QUALITY_MODE, bytes);
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "MYGALLERY");
if (!imagesFolder.exists())
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, System.currentTimeMillis()
+ ".jpg");
// write the bytes in file
try {
fo = new FileOutputStream(image);
} catch (FileNotFoundException e) {
Log.e("TAG", "FileNotFoundException", e);
// TODO Auto-generated catch block
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
Log.e("TAG", "fo.write::PictureTaken", e);
// TODO Auto-generated catch block
}
// remember close de FileOutput
try {
fo.close();
if (Build.VERSION.SDK_INT < 19)
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
else {
MediaScannerConnection
.scanFile(
getApplicationContext(),
new String[] { image.toString() },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(
String path, Uri uri) {
Log.i("ExternalStorage", "Scanned "
+ path + ":");
Log.i("ExternalStorage", "-> uri="
+ uri);
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
/*
* Toast.makeText(getApplicationContext(),
* "Your Picture has been taken !", Toast.LENGTH_LONG).show();
*/
com.integreight.onesheeld.Log.d("Camera", "Image Taken !");
if (bmp != null) {
bmp.recycle();
bmp = null;
System.gc();
}
mCamera = null;
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Your Picture has been taken !", Toast.LENGTH_SHORT)
.show();
}
});
stopSelf();
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
public void onDestroy() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if (sv != null)
windowManager.removeView(sv);
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
super.onDestroy();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (cameraIntent != null)
new TakeImage().execute(cameraIntent);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public static Bitmap decodeBitmap(byte[] data) {
Bitmap bitmap = null;
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; // Disable Dithering mode
bfOptions.inPurgeable = true; // Tell to gc that whether it needs free
// memory, the Bitmap can be cleared
bfOptions.inInputShareable = true; // Which kind of reference will be
// used to recover the Bitmap data
// after being clear, when it will
// be used in the future
bfOptions.inTempStorage = new byte[32 * 1024];
if (data != null)
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
bfOptions);
return bitmap;
}
}
You have to create a fake Surface view that doesn't appears to the users and then you can achieve by the following code
public class MainActivity extends Activity {
public static final int DONE = 1;
public static final int NEXT = 2;
public static final int PERIOD = 1;
private Camera camera;
private int cameraId = 0;
private ImageView display;
private Timer timer;
SurfaceHolder previewHolder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (ImageView) findViewById(R.id.imageView1);
// do we have a camera?
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
.show();
}
else
{
cameraId = findFrontFacingCamera();
if (cameraId < 0)
{
Toast.makeText(this, "No front facing camera found.",
Toast.LENGTH_LONG).show();
}
else
{
safeCameraOpen(cameraId);
}
}
// THIS IS JUST A FAKE SURFACE TO TRICK THE CAMERA PREVIEW
// http://stackoverflow.com/questions/17859777/how-to-take-pictures-in-android-
// application-without-the-user-interface
SurfaceView dummy = new SurfaceView(this);
previewHolder = dummy.getHolder();
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e1) {
e1.printStackTrace();
}
/*SurfaceView view = new SurfaceView(this);
try {
// camera.setPreviewDisplay(view.getHolder());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Camera.Parameters params = camera.getParameters();
params.setJpegQuality(100);
camera.setParameters(params);
// We need something to trigger periodically the capture of a
// picture to be processed
timer = new Timer(getApplicationContext(), threadHandler);
timer.execute();
}
// thread Handler //
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case DONE:
camera.startPreview();
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
camera.takePicture(null, null, mCall);
break;
case NEXT:
timer = new Timer(getApplicationContext(), threadHandler);
timer.execute();
break;
}
}
};
Camera.PictureCallback mCall = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
// display.setImageBitmap(photo);
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(data, 0,
data.length);
display.setImageBitmap(bitmapPicture);
Message.obtain(threadHandler, MainActivity.NEXT, "").sendToTarget();
// Log.v("MyActivity","Length: "+data.length);
}
};
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.v("MyActivity", "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
#Override
protected void onPause() {
if (timer != null) {
timer.cancel(true);
}
releaseCamera();
super.onPause();
}
// I think Android Documentation recommends doing this in a separate
// task to avoid blocking main UI
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
releaseCamera();
camera = Camera.open(id);
qOpened = (camera != null);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return qOpened;
}
private void releaseCamera() {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
}
If you are using CAMERA2 API (added in API 21), then kindly check my answer here Capture picture without preview using camera2 API
Hope that helped :)
You can do that using CameraX. It is used to create your own camera app so you can do that by just omitting the preview part. Go to the below link for a small tutorial on cameraX https://developer.android.com/codelabs/camerax-getting-started#0 and you can just copy paste the code. For androidx.camera.view.PreviewView just put width=0 and height=0 and you will get the required result.
For some weird reason the camera in the camerafragment is all stretched, it only appears when the theme is set to fullscreen/no action bar. Though my camera fragment has to be in fullscreen.
I have read some articles that your surfaceview should be equal to your camerapreview but when I change the resolution of the camerapreview the application crashes when entering the camerafragment.
Portrait camera:
Landscape camera:
The Camera fragment class:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.OutputStream;
/**
* Created by Gebruiker on 29-10-2014.
*/
public class SecondFragment extends Fragment {
View rootView;
ImageButton cameraShootButton;
ImageButton cameraChangeButton;
ImageButton cameraFlitsButton;
ImageButton timelineButton;
ImageButton profileButton;
ViewPager mViewPager;
Boolean switching = false;
View.OnClickListener tapper = null;
SurfaceView cameraPreview = null;
SurfaceHolder cameraPreviewHolder = null;
Camera camera = null;
boolean inPreview = false;
boolean cameraConfigured = false;
Integer currentCamera;
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.second_frag, container, false);
timelineButton = (ImageButton) rootView.findViewById(R.id.timelineB);
profileButton = (ImageButton) rootView.findViewById(R.id.profileB);
cameraShootButton = (ImageButton) rootView.findViewById(R.id.captureB);
cameraChangeButton = (ImageButton) rootView.findViewById(R.id.changeCameraB);
cameraFlitsButton = (ImageButton) rootView.findViewById(R.id.flitserB);
cameraPreview = (SurfaceView) rootView.findViewById(R.id.cameraView);
cameraPreviewHolder = cameraPreview.getHolder();
cameraPreviewHolder.addCallback(surfaceCallback);
cameraPreviewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mViewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
tapper = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.timelineB) {
mViewPager.setCurrentItem(0);
} else if (v.getId() == R.id.captureB) {
camera.takePicture(ShutterCallback, PictureCallbackRaw, null, PictureCallbackJpeg);
} else if(v.getId() == R.id.profileB){
mViewPager.setCurrentItem(2);
} else if (v.getId() == R.id.changeCameraB) {
if (switching == true){
return;
}
changeCamera();
} else if (v.getId() == R.id.flitserB){
}
}
};
cameraShootButton.setOnClickListener(tapper);
cameraChangeButton.setOnClickListener(tapper);
cameraFlitsButton.setOnClickListener(tapper);
timelineButton.setOnClickListener(tapper);
profileButton.setOnClickListener(tapper);
return rootView;
}
#Override
public void onResume() {
super.onResume();
camera = getCamera("back");
currentCamera = 1;
startPreview();
}
#Override
public void onPause() {
if (inPreview) {
camera.stopPreview();
}
camera.release();
camera = null;
inPreview = false;
super.onPause();
}
private Camera.Size getBestPreviewSize(int width, int height,
Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
if (size.width <= width && size.height <= height) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
}
return (result);
}
private void initPreview(int width, int height) {
if (camera != null && cameraPreviewHolder.getSurface() != null) {
try {
camera.setPreviewDisplay(cameraPreviewHolder);
} catch (Throwable t) {
Log.e("PreviewDemo-surfaceCallback",
"Exception in setPreviewDisplay()", t);
}
if (!cameraConfigured) {
Camera.Parameters parameters = camera.getParameters();
Log.v("CAMERA", parameters.toString());
Camera.Size size = getBestPreviewSize(width, height,
parameters);
if (size != null) {
Log.v("CameraPreviewHeight", ""+cameraPreview.getMeasuredHeight());
Log.v("CameraRES", size.width + " " + size.height);
parameters.setPreviewSize(size.width, size.height);
camera.setParameters(parameters);
cameraConfigured = true;
}
}
}
}
private void startPreview() {
if (cameraConfigured && camera != null) {
camera.startPreview();
inPreview = true;
camera.setDisplayOrientation(90);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
camera.enableShutterSound(false);
}
}
}
private void changeCamera() {
switching = true;
if (inPreview) {
camera.stopPreview();
camera.setPreviewCallback(null);
}
camera.release();
camera = null;
inPreview = false;
if (currentCamera==1){
camera = getCamera("front");
currentCamera =2;
}
else{
camera = getCamera("back");
currentCamera = 1;
}
camera.setDisplayOrientation(90);
try {
camera.setPreviewDisplay(cameraPreviewHolder);
cameraPreviewHolder.addCallback(surfaceCallback);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
inPreview = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
camera.enableShutterSound(false);
}
switching = false;
}
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
public void surfaceCreated(SurfaceHolder holder) {
// no-op -- wait until surfaceChanged()
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width,
int height) {
initPreview(width, height);
startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
};
Camera.ShutterCallback ShutterCallback = new Camera.ShutterCallback() {
public void surfaceCreated(SurfaceHolder holder) {
// no-op -- wait until surfaceChanged()
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width,
int height) {
initPreview(width, height);
startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
#Override
public void onShutter() {
}
};
Camera.PictureCallback PictureCallbackRaw = new Camera.PictureCallback() {
public void surfaceCreated(SurfaceHolder holder) {
// no-op -- wait until surfaceChanged()
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width,
int height) {
initPreview(width, height);
startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
}
};
Camera.PictureCallback PictureCallbackJpeg = new Camera.PictureCallback() {
public void surfaceCreated(SurfaceHolder holder) {
// no-op -- wait until surfaceChanged()
}
public void surfaceChanged(SurfaceHolder holder,
int format, int width,
int height) {
initPreview(width, height);
startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// no-op
}
#Override
public void onPictureTaken(byte[] byteData, Camera camera) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
OutputStream bos = null;
Bitmap m = BitmapFactory.decodeByteArray(byteData, 0, byteData.length, options);
//m.compress(Bitmap.CompressFormat.PNG, 75, bos);
//Log.v("CAPTURED", ""+bos);
}
};
private Camera getCamera(String getCamera) {
int cameraCount = 0;
Camera cam = 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) && (getCamera == "front")) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e("TEST", "Camera failed to open: " + e.getLocalizedMessage());
}
}
else if ((cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) && (getCamera == "back")) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e("TEST", "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
}
EDIT:
I've editted the onPictureTaken to:
#Override
public void onPictureTaken(byte[] byteData, Camera camera) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
OutputStream bos = null;
Bitmap bmp = BitmapFactory.decodeByteArray(byteData, 0, byteData.length, options);
FileOutputStream out = null;
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path, "TestFile.png");
try {
out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 0, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//m.compress(Bitmap.CompressFormat.PNG, 75, bos);
//Log.v("CAPTURED", ""+bos);
}
Now there is a preview of the picture on the sd card and when I check it, the result is really weird. I've taken it in portrait modus.
Zoomed in:
i am try to to capture image,which previews in a surfaceview and there is a button by which picture taken and save onto memory card.preview and capture works well but not able to store on memory card..
there are created file but picture not store one by one...
plz help me...
my try one is here....
public class MainActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
Camera mCamera;
private CameraView cameraview;
RelativeLayout mainlayout;
ImageView capture;
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cameraview = new CameraView(this, CameraInfo.CAMERA_FACING_BACK);
setContentView(R.layout.activity_main);
mainlayout = (RelativeLayout) findViewById(R.id.mainlayout);
mainlayout.addView(cameraview);
capture=(ImageView)findViewById(R.id.capture);
/////////////////////////////////////////////////////////
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
capture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
cameraview.mCamera.takePicture(shutterCallback, rawCallback,
jpegCallback);
Toast.makeText(getApplicationContext(), "Captured", 2000).show();
}
});
}
ShutterCallback shutterCallback = new ShutterCallback() {
public void onShutter() {
// Log.d(TAG, "onShutter'd");
}
};
/** Handles data for raw picture */
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//Log.d(TAG, "onPictureTaken - raw");
}
};
/** Handles data for jpeg picture */
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(String.format(
"/sdcard/Demo%d.jpg", System.currentTimeMillis()));
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
and my CameraView class is here..
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder mHolder;
Camera mCamera;
int mCameraFacingInfo;
Context m_context;
public CameraView(Context context, int camereface) {
super(context);
// TODO Auto-generated constructor stub
m_context = context;
mCameraFacingInfo = camereface;
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (mCamera != null) {
int rotation = ((Activity) m_context).getWindowManager()
.getDefaultDisplay().getRotation();
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) {
mCamera.setDisplayOrientation(90);
} else if (rotation == Surface.ROTATION_90) {
mCamera.setDisplayOrientation(0);
} else if (rotation == Surface.ROTATION_270) {
mCamera.setDisplayOrientation(180);
}
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(width, height);
// mCamera.setParameters(parameters);
mCamera.startPreview();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// ////////////////////////////////////////////////////
/*mCamera.setCameraViewDisplay(holder);
mCamera.setCameraViewCallback(new CameraViewCallback() {
public void onPreviewFrame(byte[] data, Camera arg1) {
//
CameraView.this.invalidate();
}
});
*/
// //////////////////////////////////////////
synchronized (this) {
int cameraFacingInfo = -1;
boolean errorFound = false;
boolean hasFeatCamera = m_context.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (hasFeatCamera) {
try {
cameraFacingInfo = mCameraFacingInfo;
mCamera = Camera.open(cameraFacingInfo);
} catch (Exception e) {
mCamera = Camera.open(0);
}
} else if (CameraInfo.CAMERA_FACING_FRONT > -1) {
try {
cameraFacingInfo = CameraInfo.CAMERA_FACING_FRONT;
mCamera = Camera.open(cameraFacingInfo);
} catch (Exception e) {
errorFound = true;
}
if (errorFound == true) {
try {
mCamera = Camera.open(0);
cameraFacingInfo = 0;
} catch (Exception e) {
cameraFacingInfo = -1;
}
}
}
if (cameraFacingInfo < 0) {
Toast.makeText(m_context, "No camera found.", Toast.LENGTH_LONG)
.show();
}
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(holder);
int rotation = ((Activity) m_context).getWindowManager()
.getDefaultDisplay().getRotation();
if (rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) {
// Log.i(TAG, "0");
mCamera.setDisplayOrientation(90);
} else if (rotation == Surface.ROTATION_90) {
// Log.i(TAG, "90");
mCamera.setDisplayOrientation(0);
} else if (rotation == Surface.ROTATION_270) {
// Log.i(TAG, "270");
mCamera.setDisplayOrientation(180);
}
} catch (IOException exception) {
mCamera.release();
mCamera = null;
// TODO: add more exception handling logic here
}
}
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public void setCameraFacingInfo(int cameraFacingInfo) {
mCameraFacingInfo = cameraFacingInfo;
}
}
Try to change your jpegCallback class to this:
PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
//Creating empty file in sdcard
File pictureFile = new File(String.format("/sdcard/Demo%d.jpg", System.currentTimeMillis()));
if (pictureFile == null) {
Log.e("IMAGE CAPTURE", "Error creating media file, check storage permissions: ");
return;
}
if (data != null) {
BitmapFactory.Options opts = new BitmapFactory.Options();
ActivityManager activityManager = (ActivityManager) MainActivity.this.getSystemService(Activity.ACTIVITY_SERVICE);
int memoryLimit = 100;
if (activityManager != null) {
memoryLimit = activityManager.getMemoryClass();
}
// Considering memory limitation of device we will resize image to prevent OutOfMemory
if (memoryLimit < 20) {
opts.inSampleSize = 6;
} else if (memoryLimit < 40) {
opts.inSampleSize = 4;
} else if (memoryLimit < 64) {
opts.inSampleSize = 2;
}
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos)) {
fos.close();
}
bitmap.recycle();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
}
I have an android app which consists of a Button.
When you click on Button, an image should be captured from the camera without opening the camera application (the image should be captured in background).
How to implement this feature?
Any suggestions will be of great help.
Thanks a lot in advance.
Here is my whole working project of How to capture image in background without SurfaceView.
// You can start your service to capturing image wherever you want not should from activity.
also need to ask need permission in your Activity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, APP_PERMISSION_REQUEST);
}
handle intent in click or where you needed
Intent front_translucent = new Intent(getApplication()
.getApplicationContext(), CameraService.class);
front_translucent.putExtra("Front_Request", true);
front_translucent.putExtra("Quality_Mode",
camCapture.getQuality());
getApplication().getApplicationContext().startService(
front_translucent);
public class CamerService extends Service implements
SurfaceHolder.Callback {
// Camera variables
// a surface holder
// a variable to control the camera
private Camera mCamera;
// the camera parameters
private Parameters parameters;
private Bitmap bmp;
FileOutputStream fo;
private String FLASH_MODE;
private int QUALITY_MODE = 0;
private boolean isFrontCamRequest = false;
private Camera.Size pictureSize;
SurfaceView sv;
private SurfaceHolder sHolder;
private WindowManager windowManager;
WindowManager.LayoutParams params;
public Intent cameraIntent;
SharedPreferences pref;
Editor editor;
int width = 0, height = 0;
/** Called when the activity is first created. */
#Override
public void onCreate() {
super.onCreate();
}
private Camera openFrontFacingCameraGingerbread() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
}
int cameraCount = 0;
Camera cam = 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 {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e("Camera",
"Camera failed to open: " + e.getLocalizedMessage());
/*
* Toast.makeText(getApplicationContext(),
* "Front Camera failed to open", Toast.LENGTH_LONG)
* .show();
*/
}
}
}
return cam;
}
private void setBesttPictureResolution() {
// get biggest picture size
width = pref.getInt("Picture_Width", 0);
height = pref.getInt("Picture_height", 0);
if (width == 0 | height == 0) {
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// save width and height in sharedprefrences
width = pictureSize.width;
height = pictureSize.height;
editor.putInt("Picture_Width", width);
editor.putInt("Picture_height", height);
editor.commit();
} else {
// if (pictureSize != null)
parameters.setPictureSize(width, height);
}
}
private Camera.Size getBiggesttPictureSize(Camera.Parameters parameters) {
Camera.Size result = null;
for (Camera.Size size : parameters.getSupportedPictureSizes()) {
if (result == null) {
result = size;
} else {
int resultArea = result.width * result.height;
int newArea = size.width * size.height;
if (newArea > resultArea) {
result = size;
}
}
}
return (result);
}
/** Check if this device has a camera */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** Check if this device has front camera */
private boolean checkFrontCamera(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FRONT)) {
// this device has front camera
return true;
} else {
// no front camera on this device
return false;
}
}
Handler handler = new Handler();
private class TakeImage extends AsyncTask<Intent, Void, Void> {
#Override
protected Void doInBackground(Intent... params) {
takeImage(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
private synchronized void takeImage(Intent intent) {
if (checkCameraHardware(getApplicationContext())) {
Bundle extras = intent.getExtras();
if (extras != null) {
String flash_mode = extras.getString("FLASH");
FLASH_MODE = flash_mode;
boolean front_cam_req = extras.getBoolean("Front_Request");
isFrontCamRequest = front_cam_req;
int quality_mode = extras.getInt("Quality_Mode");
QUALITY_MODE = quality_mode;
}
if (isFrontCamRequest) {
// set flash 0ff
FLASH_MODE = "off";
// only for gingerbread and newer versions
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(sv.getHolder());
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
Camera.Parameters parameters = mCamera.getParameters();
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
// return 4;
} else {
mCamera = null;
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Your Device dosen't have Front Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
/*
* sHolder = sv.getHolder(); // tells Android that this
* surface will have its data // constantly // replaced if
* (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
*/
} else {
if (checkFrontCamera(getApplicationContext())) {
mCamera = openFrontFacingCameraGingerbread();
if (mCamera != null) {
try {
mCamera.setPreviewDisplay(sv.getHolder());
} catch (IOException e) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"API dosen't support front camera",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
Camera.Parameters parameters = mCamera.getParameters();
pictureSize = getBiggesttPictureSize(parameters);
if (pictureSize != null)
parameters
.setPictureSize(pictureSize.width, pictureSize.height);
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
// return 4;
} else {
mCamera = null;
/*
* Toast.makeText(getApplicationContext(),
* "API dosen't support front camera",
* Toast.LENGTH_LONG).show();
*/
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(
getApplicationContext(),
"Your Device dosen't have Front Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
// Get a surface
/*
* sHolder = sv.getHolder(); // tells Android that this
* surface will have its data // constantly // replaced
* if (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS
* );
*/
}
}
} else {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = Camera.open();
} else
mCamera = getCameraInstance();
try {
if (mCamera != null) {
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
if (FLASH_MODE == null || FLASH_MODE.isEmpty()) {
FLASH_MODE = "auto";
}
parameters.setFlashMode(FLASH_MODE);
// set biggest picture
setBesttPictureResolution();
// log quality and image format
Log.d("Qaulity", parameters.getJpegQuality() + "");
Log.d("Format", parameters.getPictureFormat() + "");
// set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
Log.d("ImageTakin", "OnTake()");
mCamera.takePicture(null, null, mCall);
} else {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Camera is unavailable !",
Toast.LENGTH_LONG).show();
}
});
}
// return 4;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TAG", "CmaraHeadService()::takePicture", e);
}
// Get a surface
/*
* sHolder = sv.getHolder(); // tells Android that this surface
* will have its data constantly // replaced if
* (Build.VERSION.SDK_INT < 11)
*
* sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
*/
}
} else {
// display in long period of time
/*
* Toast.makeText(getApplicationContext(),
* "Your Device dosen't have a Camera !", Toast.LENGTH_LONG)
* .show();
*/
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Your Device dosen't have a Camera !",
Toast.LENGTH_LONG).show();
}
});
stopSelf();
}
// return super.onStartCommand(intent, flags, startId);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// sv = new SurfaceView(getApplicationContext());
cameraIntent = intent;
Log.d("ImageTakin", "StartCommand()");
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.width = 1;
params.height = 1;
params.x = 0;
params.y = 0;
sv = new SurfaceView(getApplicationContext());
windowManager.addView(sv, params);
sHolder = sv.getHolder();
sHolder.addCallback(this);
// tells Android that this surface will have its data constantly
// replaced
if (Build.VERSION.SDK_INT < 11)
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
return 1;
}
Camera.PictureCallback mCall = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
Log.d("ImageTakin", "Done");
if (bmp != null)
bmp.recycle();
System.gc();
bmp = decodeBitmap(data);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
if (bmp != null && QUALITY_MODE == 0)
bmp.compress(Bitmap.CompressFormat.JPEG, 70, bytes);
else if (bmp != null && QUALITY_MODE != 0)
bmp.compress(Bitmap.CompressFormat.JPEG, QUALITY_MODE, bytes);
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "MYGALLERY");
if (!imagesFolder.exists())
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, System.currentTimeMillis()
+ ".jpg");
// write the bytes in file
try {
fo = new FileOutputStream(image);
} catch (FileNotFoundException e) {
Log.e("TAG", "FileNotFoundException", e);
// TODO Auto-generated catch block
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
Log.e("TAG", "fo.write::PictureTaken", e);
// TODO Auto-generated catch block
}
// remember close de FileOutput
try {
fo.close();
if (Build.VERSION.SDK_INT < 19)
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
else {
MediaScannerConnection
.scanFile(
getApplicationContext(),
new String[] { image.toString() },
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(
String path, Uri uri) {
Log.i("ExternalStorage", "Scanned "
+ path + ":");
Log.i("ExternalStorage", "-> uri="
+ uri);
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
/*
* Toast.makeText(getApplicationContext(),
* "Your Picture has been taken !", Toast.LENGTH_LONG).show();
*/
com.integreight.onesheeld.Log.d("Camera", "Image Taken !");
if (bmp != null) {
bmp.recycle();
bmp = null;
System.gc();
}
mCamera = null;
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Your Picture has been taken !", Toast.LENGTH_SHORT)
.show();
}
});
stopSelf();
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
public void onDestroy() {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if (sv != null)
windowManager.removeView(sv);
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
super.onDestroy();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (cameraIntent != null)
new TakeImage().execute(cameraIntent);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
public static Bitmap decodeBitmap(byte[] data) {
Bitmap bitmap = null;
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; // Disable Dithering mode
bfOptions.inPurgeable = true; // Tell to gc that whether it needs free
// memory, the Bitmap can be cleared
bfOptions.inInputShareable = true; // Which kind of reference will be
// used to recover the Bitmap data
// after being clear, when it will
// be used in the future
bfOptions.inTempStorage = new byte[32 * 1024];
if (data != null)
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
bfOptions);
return bitmap;
}
}
You have to create a fake Surface view that doesn't appears to the users and then you can achieve by the following code
public class MainActivity extends Activity {
public static final int DONE = 1;
public static final int NEXT = 2;
public static final int PERIOD = 1;
private Camera camera;
private int cameraId = 0;
private ImageView display;
private Timer timer;
SurfaceHolder previewHolder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (ImageView) findViewById(R.id.imageView1);
// do we have a camera?
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
{
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
.show();
}
else
{
cameraId = findFrontFacingCamera();
if (cameraId < 0)
{
Toast.makeText(this, "No front facing camera found.",
Toast.LENGTH_LONG).show();
}
else
{
safeCameraOpen(cameraId);
}
}
// THIS IS JUST A FAKE SURFACE TO TRICK THE CAMERA PREVIEW
// http://stackoverflow.com/questions/17859777/how-to-take-pictures-in-android-
// application-without-the-user-interface
SurfaceView dummy = new SurfaceView(this);
previewHolder = dummy.getHolder();
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e1) {
e1.printStackTrace();
}
/*SurfaceView view = new SurfaceView(this);
try {
// camera.setPreviewDisplay(view.getHolder());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Camera.Parameters params = camera.getParameters();
params.setJpegQuality(100);
camera.setParameters(params);
// We need something to trigger periodically the capture of a
// picture to be processed
timer = new Timer(getApplicationContext(), threadHandler);
timer.execute();
}
// thread Handler //
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case DONE:
camera.startPreview();
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
try {
camera.setPreviewDisplay(previewHolder);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
camera.takePicture(null, null, mCall);
break;
case NEXT:
timer = new Timer(getApplicationContext(), threadHandler);
timer.execute();
break;
}
}
};
Camera.PictureCallback mCall = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// decode the data obtained by the camera into a Bitmap
// display.setImageBitmap(photo);
Bitmap bitmapPicture = BitmapFactory.decodeByteArray(data, 0,
data.length);
display.setImageBitmap(bitmapPicture);
Message.obtain(threadHandler, MainActivity.NEXT, "").sendToTarget();
// Log.v("MyActivity","Length: "+data.length);
}
};
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.v("MyActivity", "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
#Override
protected void onPause() {
if (timer != null) {
timer.cancel(true);
}
releaseCamera();
super.onPause();
}
// I think Android Documentation recommends doing this in a separate
// task to avoid blocking main UI
private boolean safeCameraOpen(int id) {
boolean qOpened = false;
try {
releaseCamera();
camera = Camera.open(id);
qOpened = (camera != null);
} catch (Exception e) {
Log.e(getString(R.string.app_name), "failed to open Camera");
e.printStackTrace();
}
return qOpened;
}
private void releaseCamera() {
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
}
}
If you are using CAMERA2 API (added in API 21), then kindly check my answer here Capture picture without preview using camera2 API
Hope that helped :)
You can do that using CameraX. It is used to create your own camera app so you can do that by just omitting the preview part. Go to the below link for a small tutorial on cameraX https://developer.android.com/codelabs/camerax-getting-started#0 and you can just copy paste the code. For androidx.camera.view.PreviewView just put width=0 and height=0 and you will get the required result.