Introduction:
Here I am going to explain how to take pictures from camera without users interactions. We just need to start an activity for result. This activity will have a surface view & this activity will start camera for preview for capturing image.an image should be captured from the camera without opening the camera application (the image should be captured in background).
demo
Using this code
MainActivity.java
package
com.example.captureimagewithoutsurfaceview;
import
android.app.Activity;
import
android.content.Context;
import
android.content.Intent;
import
android.os.Bundle;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.ImageView;
public
class
MainActivity extends
Activity {
public
static
int
cameraID;
public
static
ImageView
imgCapture;
Button
btnFront,btnBack;
Context
context;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
imgCapture
= (ImageView) findViewById(R.id.imageView1);
btnFront=(Button)findViewById(R.id.button1);
btnBack=(Button)findViewById(R.id.button2);
btnFront.setOnClickListener(new
OnClickListener() {
@Override
public
void
onClick(View v) {
//
TODO
Auto-generated method stub
cameraID
= 1;
Intent
i = new
Intent(context,CameraView.class);
startActivity(i);
}
});
btnBack.setOnClickListener(new
OnClickListener() {
@Override
public
void
onClick(View v) {
//
TODO
Auto-generated method stub
cameraID
= 0;
Intent
i = new
Intent(context,CameraView.class);
startActivity(i);
}
});
}
}
activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button2"
android:layout_centerInParent="true"
android:text="Capture
using Front Camera" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:layout_marginBottom="20dp"
android:text="Capture
using Back Camera" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
/>
</RelativeLayout>
CameraView.java
package
com.example.captureimagewithoutsurfaceview;
Camera
mCamera;
Camera.PictureCallback
mPictureCallback
= new
Camera.PictureCallback()
{
Camera.Parameters
p = mCamera.getParameters();
import
java.io.File;
import
java.io.FileNotFoundException;
import
java.io.FileOutputStream;
import
java.text.SimpleDateFormat;
import
java.util.Calendar;
import
android.annotation.TargetApi;
import
android.app.Activity;
import
android.content.Context;
import
android.graphics.Bitmap;
import
android.graphics.BitmapFactory;
import
android.graphics.Matrix;
import
android.graphics.PixelFormat;
import
android.hardware.Camera;
import
android.os.Bundle;
import
android.os.Environment;
import
android.provider.MediaStore;
import
android.util.Log;
import
android.view.SurfaceHolder;
import
android.view.SurfaceView;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.view.Window;
import
android.view.WindowManager;
public
class
CameraView extends
Activity implements
SurfaceHolder.Callback, OnClickListener{
private
static
final
String TAG
= "CameraTest";
boolean
mPreviewRunning
= false;
Context
context;
@SuppressWarnings("deprecation")
public
void
onCreate(Bundle icicle){
super.onCreate(icicle);
Log.e(TAG,
"onCreate");
getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.view);
context=this;
mSurfaceView
= (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceView.setOnClickListener(this);
mSurfaceHolder
= mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
protected
void
onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
public
void
onPictureTaken(byte[]
data, Camera
camera) {
//
TODO
Auto-generated method stub
if
(data != null){
mCamera.stopPreview();
mPreviewRunning
= false;
mCamera.release();
try{
BitmapFactory.Options
opts = new
BitmapFactory.Options();
Bitmap
bitmap= BitmapFactory.decodeByteArray(data,
0, data.length,opts);
bitmap
= Bitmap.createScaledBitmap(bitmap,
300, 300, false);
int
width = bitmap.getWidth();
int
height = bitmap.getHeight();
int
newWidth = 300;
int
newHeight = 300;
//
calculate the scale - in this case = 0.4f
float
scaleWidth = ((float)
newWidth) / width;
float
scaleHeight = ((float)
newHeight) / height;
//
createa
matrix for the manipulation
Matrix
matrix = new
Matrix();
//
resize the bit map
matrix.postScale(scaleWidth,
scaleHeight);
//
rotate the Bitmap
matrix.postRotate(-90);
Bitmap
resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
width,
height, matrix, true);
MainActivity.imgCapture.setImageBitmap(resizedBitmap);
Calendar
c = Calendar.getInstance();
SimpleDateFormat
sdf = new
SimpleDateFormat("yyyy-MM-dd
HH:mm:ss");
String
currentDateandTime = sdf.format(c.getTime());
Log.e("currentDateandTime",
""
+ currentDateandTime);
File
mydir = new
File(Environment.getExternalStorageDirectory()
+ "/CAPTURED_IMAGES/");
if(!mydir.exists())
{
mydir.mkdirs();
String extr = Environment.getExternalStorageDirectory().toString()
+ File.separator
+ "CAPTURED_IMAGES";
File myPath = new
File(extr, currentDateandTime+".jpg");
FileOutputStream fos = null;
try
{
fos = new
FileOutputStream(myPath);
resizedBitmap.compress(Bitmap.CompressFormat.JPEG,
100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(context.getContentResolver(),
resizedBitmap, myPath.getPath(), currentDateandTime);
} catch
(FileNotFoundException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
} catch
(Exception e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
else
{
Log.d("error",
"dir. already exists");
String
extr = Environment.getExternalStorageDirectory().toString()
+ File.separator
+ "CAPTURED_IMAGES";
File myPath = new
File(extr, currentDateandTime+".jpg");
FileOutputStream fos = null;
try
{
fos = new
FileOutputStream(myPath);
resizedBitmap.compress(Bitmap.CompressFormat.JPEG,
100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(context.getContentResolver(),
resizedBitmap, myPath.getPath(), currentDateandTime);
} catch
(FileNotFoundException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
} catch
(Exception e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}catch(Exception
e){
e.printStackTrace();
}
//StoreByteImage(mContext,
imageData, 50,"ImageName");
//setResult(FOTO_MODE,
mIntent);
setResult(585);
finish();
}
}
};
protected
void
onResume(){
Log.e(TAG,
"onResume");
super.onResume();
}
protected
void
onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
}
protected
void
onStop(){
Log.e(TAG,
"onStop");
super.onStop();
}
@TargetApi(9)
public
void
surfaceCreated(SurfaceHolder holder){
Log.e(TAG,
"surfaceCreated");
mCamera
= Camera.open(MainActivity.cameraID);
}
public
void
surfaceChanged(SurfaceHolder holder, int
format, int
w, int
h) {
Log.e(TAG,
"surfaceChanged");
//
XXX
stopPreview() will crash if preview is not running
if
(mPreviewRunning){
mCamera.stopPreview();
}
p.setPreviewSize(300,
300);
mCamera.setParameters(p);
try{
mCamera.setPreviewDisplay(holder);
}catch
(Exception e){
//
TODO
Auto-generated catch block
e.printStackTrace();
}
mCamera.startPreview();
mPreviewRunning
= true;
mCamera.takePicture(null,
mPictureCallback,
mPictureCallback);
}
public
void
surfaceDestroyed(SurfaceHolder holder) {
Log.e(TAG,
"surfaceDestroyed");
}
private
SurfaceView mSurfaceView;
private
SurfaceHolder mSurfaceHolder;
public
void
onClick(View v) {
//
TODO
Auto-generated method stub
mCamera.takePicture(null,
mPictureCallback,
mPictureCallback);
}
}
Androidmanifest.xml
<?xml
version="1.0"
encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.captureimagewithoutsurfaceview"
android:versionCode="1"
android:versionName="1.0"
>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15"
/>
<uses-permission
android:name="android.permission.CAMERA"
/>
<uses-feature
android:name="android.hardware.camera"
/>
<uses-feature
android:name="android.hardware.camera.autofocus"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
>
<intent-filter>
<action
android:name="android.intent.action.MAIN"
/>
<category
android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
<activity
android:name=".CameraView"
/>
</application>
</manifest>
EmoticonEmoticon