public class CustomCameraActivity extends Activity implements
SurfaceHolder.Callback {
Camera camera = null;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
int flag = 0;
int which = 0;
Handler handler;
private boolean hasFlash;
private boolean isLighOn;
private Bitmap surfaceBitmap;
private Bitmap cameraBitmap;
private VerticalSeekBar greenSeekbar;
int vesion = 0;
public void turn() {
// myCamera is the Camera object
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
// only for android older than gingerbread
if (Camera.getNumberOfCameras() >= 2) {
vesion = 1;
camera.stopPreview();
camera.release();
// "which" is just an integer flag
switch (which) {
case 0:
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
which = 1;
break;
case 1:
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
which = 0;
break;
}
try {
camera.setPreviewDisplay(surfaceHolder);
// "this" is a SurfaceView which implements
// SurfaceHolder.Callback,
// as found in the code examples
camera.setPreviewCallback(null);
// camera.setPreviewCallback(this);
camera.startPreview();
} catch (IOException exception) {
camera.release();
camera = null;
}
vesion = 1;
} else {
AlertDialog.Builder ab = new AlertDialog.Builder(
CustomCameraActivity.this);
ab.setMessage("Device Having Only one Camera");
ab.setCancelable(false);
ab.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
}).show();
}
} else {
AlertDialog.Builder ab1 = new AlertDialog.Builder(
CustomCameraActivity.this);
ab1.setMessage("This Device Does Not Support Dual Camera Feature");
ab1.setCancelable(false);
ab1.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Constants.data1 = data;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(3);
this.surfaceView.setBackgroundColor(Color.argb(100, 0,
MotionEventCompat.ACTION_MASK, 0));
Button cap_btn = (Button) findViewById(R.id.button01);
Button retake = (Button) findViewById(R.id.retake);
Button use = (Button) findViewById(R.id.Use);
Button back = (Button) findViewById(R.id.back);
Button home = (Button) findViewById(R.id.home);
Button turn = (Button) findViewById(R.id.turn);
turn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
turn();
}
});
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flash();
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
use.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (flag >= 1) {
startActivity(new Intent(CustomCameraActivity.this,
Captured.class));
} else {
AlertDialog.Builder ab1 = new AlertDialog.Builder(
CustomCameraActivity.this);
ab1.setMessage("Please Capture Image");
ab1.setCancelable(false);
ab1.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
}).show();
}
flag = 0;
}
});
retake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.startPreview();
flag = 0;
}
});
cap_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.takePicture(null, null, mPicture);
flag++;
}
});
}
public void flash() {
this.hasFlash = getApplicationContext().getPackageManager()
.hasSystemFeature("android.hardware.camera.flash");
if (this.hasFlash) {
Parameters p = camera.getParameters();
if (this.isLighOn) {
p.setFlashMode("off");
camera.setParameters(p);
camera.stopPreview();
camera.startPreview();
this.isLighOn = false;
return;
}
p.setFlashMode("torch");
camera.setParameters(p);
camera.stopPreview();
camera.startPreview();
this.isLighOn = true;
return;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
void setCameraDisplayOrientation(Activity activity, int cameraId,
Camera camera) {
if (camera != null) {
int result;
CameraInfo info = new CameraInfo();
int degrees = 0;
switch (activity.getWindowManager().getDefaultDisplay()
.getRotation()) {
case 0:
degrees = 0;
break;
case 1:
degrees = 90;
break;
case 2:
degrees = 180;
break;
case 3:
degrees = 270;
break;
}
if (info.facing == 1) {
result = (360 - ((info.orientation + degrees) % 360)) % 360;
} else {
result = ((info.orientation - degrees) + 360) % 360;
}
camera.setDisplayOrientation(result);
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (vesion == 1) {
Camera.open(which);
} else {
camera = Camera.open();
}
} catch (Exception e) {
camera.release();
}
try {
Parameters parameters = camera.getParameters();
if (getResources().getConfiguration().orientation != 2) {
parameters.set("orientation", "portrait");
camera.setDisplayOrientation(90);
parameters.setRotation(90);
} else {
parameters.set("orientation", "landscape");
camera.setDisplayOrientation(0);
parameters.setRotation(0);
}
camera.setParameters(parameters);
camera.setPreviewDisplay(this.surfaceHolder);
} catch (IOException e2) {
camera.release();
}
camera.startPreview();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
public void joinBitmap() {
this.surfaceView.setBackgroundColor(-16711936);
this.surfaceView.setDrawingCacheEnabled(true);
this.surfaceView.buildDrawingCache();
this.surfaceView.refreshDrawableState();
new Thread() {
public void run() {
try {
CustomCameraActivity.this.surfaceBitmap = CustomCameraActivity.this.surfaceView
.getDrawingCache();
if (CustomCameraActivity.this.surfaceBitmap != null) {
File pictureFile = CustomCameraActivity
.getOutputMediaFile();
if (pictureFile != null) {
Bitmap finalbitmap = CustomCameraActivity.overlay(
CustomCameraActivity.this.cameraBitmap,
CustomCameraActivity.this.surfaceBitmap,
CustomCameraActivity.this.greenSeekbar
.getProgress() + 15);
if (pictureFile.exists()) {
pictureFile.delete();
}
try {
FileOutputStream out = new FileOutputStream(
pictureFile);
finalbitmap.compress(CompressFormat.JPEG, 90,
out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
} catch (IOException e2) {
}
CustomCameraActivity.this.handler
.sendEmptyMessage(1);
return;
}
return;
}
CustomCameraActivity.this.handler.sendEmptyMessage(0);
} catch (Exception e3) {
}
}
}.start();
}
#SuppressLint({ "SimpleDateFormat" })
private static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(),
"Night Vision Camera");
if (mediaStorageDir.exists() || mediaStorageDir.mkdirs()) {
return new File(
mediaStorageDir.getPath()
+ File.separator
+ "IMG_"
+ new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date()) + ".jpg");
}
return null;
}
public static Bitmap overlay(Bitmap bitmap1, Bitmap bitmapOverlay,
int opacity) {
Bitmap resultBitmap = Bitmap.createBitmap(bitmapOverlay.getWidth(),
bitmapOverlay.getHeight(), Config.ARGB_8888);
Canvas c = new Canvas(resultBitmap);
c.drawBitmap(bitmap1, 0.0f, 0.0f, null);
Paint p = new Paint();
p.setAlpha(opacity);
c.drawBitmap(bitmapOverlay, 0.0f, 0.0f, p);
return resultBitmap;
}
}
Here, I`m creating an image overlay on surface view and when i click on image to capture it, how to save it with that image that is overlayed on it? Please help and thanks in Advance. The image is captured but it is not saved with that image that is overlayed on the surface view.
You can use surfaceview.getDrawingCache();
this will return a Bitmap from your SurfaceView and then you can use it or save it in storage.
surfaceview.getDrawingCache(); does not work on surface, because surface is separate view than others view you have to get bitmpa on picturetaken method.
jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
camera.startPreview();
Bitmap cameraBitmap = BitmapFactory.decodeByteArray
(data, 0, data.length);
Matrix matrix = new Matrix();
matrix.postRotate(90);
pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setTitle("Wait!");
pd.setMessage("capturing image.........");
pd.setIndeterminate(false);
pd.show();
progressStatus = 0;
new Thread(new Runnable() {
#Override
public void run() {
while (progressStatus < 100) {
// Update the progress status
progressStatus += 1;
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
// Update the progress status
pd.setProgress(progressStatus);
// If task execution completed
if (progressStatus == 100) {
// Dismiss/hide the progress dialog
pd.dismiss();
}
}
});
}
}
}).start();
Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
if (rotatedBitmap != null) {
rotatedBitmap = combinebitmap(rotatedBitmap, bitmapMap);
Random num = new Random();
int nu = num.nextInt(1000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
String picId = String.valueOf(nu);
String myfile = "Ghost" + picId + ".jpeg";
File dir_image = new File(Environment.getExternalStorageDirectory() +//<---
File.separator + "LiveCamera"); //<---
dir_image.mkdirs(); //<---
try {
File tmpFile = new File(dir_image, myfile);
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
Toast.makeText(getApplicationContext(),
" Image saved at :LiveCamera", Toast.LENGTH_LONG).show();
camera.startPreview();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(MainActivity.this,
new String[]{dir_image.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
safeToTakePicture = true;
}
}
};
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.
I need to create an app where when I click a photo it will save 3 jpegs is different focus modes(auto focus, Macro focus and Infinite focus) if possible and save it. I have made a basic camera app whoe code I am posting..Can you guys tell me how to implement this?
public class MainActivity extends Activity implements Constants,SurfaceHolder.Callback,Camera.PreviewCallback,
Camera.AutoFocusCallback, OnTouchListener{
private ViewFlipper myviewflipper;
private float initialXpoint;
private Camera mCamera;
private SurfaceView mPreviewSV;
private SurfaceHolder mSurfaceHolder;
private Button mCapture;
private Button mChange;
private Button mReturn;
private Button mLoad;
private ImageView mImageView;
private int mPicturesCaptured = 0;
boolean isCaptureClicked = false;
boolean encodingCompleted = false;
long startTime;
int currentFile = 0;
int initialPointer = -1;
int secondPointer = -1;
int direction = -1;
CameraSize picSize = BACK_CAM_PREVIEW_SIZE_3 ;
File mFile;
ArrayList<String> imagePath;
ProgressDialog mEncodingProgress;
DisplayTask mTask;
Bitmap mDisplayBitmap;
File path;
File[] files;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mFile = new File(Constants.Cameraeffect);
if (!mFile.exists())
mFile.mkdir();
setupUI();
}
private void setupUI()
{
mPreviewSV = (SurfaceView) findViewById(R.id.sv_cam_preview);
mCapture = (Button) findViewById(R.id.button_capture);
mChange = (Button) findViewById(R.id.toggle);
mReturn = (Button) findViewById(R.id.button_return);
mImageView = (ImageView) findViewById(R.id.display);
mImageView.setOnTouchListener(this);
mLoad = (Button) findViewById(R.id.button_load);
mSurfaceHolder = mPreviewSV.getHolder();
mSurfaceHolder.addCallback(this);
mCapture.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
deleteFiles();
mPicturesCaptured = 0;
isCaptureClicked = true;
startTime=System.currentTimeMillis();
progressUpdate();
}
});
mChange.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
int res = getCurrentCameraId();
switch(res){
case 0:
stopCamera();
startCamera(Constants.FRONT_CAMERA);
break;
case 1:
stopCamera();
startCamera(Constants.BACK_CAMERA);
break;
}
}
});
mLoad.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
imagePath=ListAllFiles();
mImageView.bringToFront();
mImageView.setVisibility(View.VISIBLE);
mImageView.setImageBitmap(decodeFile(imagePath.get(0)));
mTask = new DisplayTask();
mTask.execute("");
}
});
mReturn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
}
private ArrayList<String> ListAllFiles() {
ArrayList<String> tFileList = new ArrayList<String>();
path= new File(Constants.Cameraeffect);
if( path.exists() ) {
files = path.listFiles();
for(int i=0; i<files.length; i++) {
tFileList.add(files[i].toString());
}
}
return tFileList;
}
public void deleteFiles() {
path= new File(Constants.Cameraeffect);
if( path.exists() ) {
files = path.listFiles();
for(int i=0; i<files.length; i++) {
files[i].delete();
}
}
}
#SuppressWarnings("unused")
int getCurrentCameraId() {
int mCameraId = -1;
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_BACK){
return Constants.BACK_CAMERA;
}
else if (ci.facing == CameraInfo.CAMERA_FACING_FRONT){
return Constants.FRONT_CAMERA;
}
}
return -1;
}
private void progressUpdate()
{
mEncodingProgress = new ProgressDialog(this);
mEncodingProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mEncodingProgress.setMessage("Encoding");
mEncodingProgress.setIndeterminate(false);
mEncodingProgress.show();
new Thread(new Runnable()
{
public void run()
{
while((System.currentTimeMillis()-startTime)<=5000)
{
try
{
Thread.sleep(10);
mEncodingProgress.setProgress(mPicturesCaptured + 1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}).start();
}
#SuppressWarnings("unused")
private void startCamera(int id)
{
try
{
if (mCamera != null)
stopCamera();
mCamera = Camera.open(id);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(1280,720);
parameters.setFocusMode("infinite");
parameters.setJpegQuality(100);
parameters.setAutoExposureLock(true);
parameters.setAutoWhiteBalanceLock(true);
parameters.setRotation(0);
mCamera.setDisplayOrientation(0);
mCamera.setParameters(parameters);
mCamera.setPreviewCallback(this);
mCamera.setPreviewDisplay(mPreviewSV.getHolder());
mCamera.startPreview();
}
catch (IOException e)
{
stopCamera();
}
}
private void stopCamera()
{
if (mCamera != null)
{
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mPreviewSV.getHolder().removeCallback(this);
mCamera.release();
mCamera = null;
}
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
}
#Override
protected void onPause()
{
stopCamera();
super.onPause();
}
#Override
protected void onDestroy()
{
stopCamera();
super.onDestroy();
}
public void surfaceCreated(SurfaceHolder holder)
{
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
startCamera(0);
}
public void surfaceDestroyed(SurfaceHolder holder)
{
}
public void onPreviewFrame(byte[] data, Camera camera)
{
if (System.currentTimeMillis()-startTime<=5000)
{
savingJpegToSDCard(data);
}
else
{
if(mEncodingProgress!=null){
mEncodingProgress.dismiss();
mEncodingProgress=null;
encodingCompleted=true;
}
}
if(encodingCompleted){
/*
* Log.i("","sent to JNI");
*/
encodingCompleted=false;
}
}
public void onAutoFocus(boolean arg0, Camera arg1) {
// TODO Auto-generated method stub
}
public boolean onTouch(View arg0, MotionEvent event) {
Log.d("","srikrishna:: ontouch");
switch(event.getAction()){
case(MotionEvent.ACTION_DOWN):
initialPointer=(int) event.getX();
break;
case(MotionEvent.ACTION_MOVE):
secondPointer=(int) event.getX();
break;
case(MotionEvent.ACTION_UP):
initialPointer=(int) event.getX();
}
return true;
}
public Bitmap decodeFile(String fPath)
{
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
opts.inDither = false;
opts.inPurgeable = true;
opts.inInputShareable = true;
BitmapFactory.decodeFile(fPath, opts);
final int REQUIRED_SIZE = 500;
int scale = 1;
if (opts.outHeight > REQUIRED_SIZE || opts.outWidth > REQUIRED_SIZE)
{
final int heightRatio = Math
.round((float) opts.outHeight / (float) REQUIRED_SIZE);
final int widthRatio = Math
.round((float) opts.outWidth / (float) REQUIRED_SIZE);
scale = heightRatio < widthRatio ? heightRatio : widthRatio;//
}
opts.inJustDecodeBounds = false;
opts.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile(fPath, opts).copy(
Bitmap.Config.RGB_565, false);
return bm;
}
private void savingJpegToSDCard(final byte[] b1)
{
try{
Camera.Parameters parameters = mCamera.getParameters();
Size size = parameters.getPreviewSize();
Log.i("","abh size width and height "+size.width + " "+size.height);
YuvImage image = new YuvImage(b1, parameters.getPreviewFormat(),size.width, size.height, null);
File file = new File(Constants.Cameraeffect + "/File" + mPicturesCaptured + ".jpeg");
FileOutputStream filecon = new FileOutputStream(file);
image.compressToJpeg(new Rect(0, 0, image.getWidth(), image.getHeight()), 90,filecon);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
mPicturesCaptured++;
}
class DisplayTask extends AsyncTask<String, Bitmap, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
currentFile = 0;
}
#Override
protected Void doInBackground(String... params)
{
while(true){
Log.i("","abh imagePath.size() "+imagePath.size());
if(secondPointer-initialPointer >50)
{
Log.i("","abh currentFile "+currentFile);
mDisplayBitmap = decodeFile(imagePath.get(currentFile));
publishProgress(mDisplayBitmap);
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
if(currentFile<=90)
currentFile++;
initialPointer=secondPointer;
}
}
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Bitmap... values)
{
super.onProgressUpdate(values);
mImageView.setImageBitmap(values[0]);
}
}
}
In your start camera method set the focus mode to the required one and start the camera. If you want to change it dynamically on click of button then you must call the start camera method with the required attributes. Make sure you are releasing camera[this is very imp] also note that the custom camera implementation in android is very buggy[many of the bugs are stil open just goggle it and see] i suggest you read it carefully and implement it.
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.