J'ai utilisé ce code pour capturer une image de la caméra.
package Android.takeowneship;
import Java.io.File;
import Android.app.Activity;
import Android.content.ContentValues;
import Android.content.Intent;
import Android.database.Cursor;
import Android.graphics.Bitmap;
import Android.graphics.BitmapFactory;
import Android.net.Uri;
import Android.os.Bundle;
import Android.provider.MediaStore;
import Android.widget.ImageView;
import Android.widget.Toast;
public class camera extends Activity{
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
Uri imageUri;
private ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//define the file-name to save photo taken by Camera activity
String fileName = "new-photo-name.jpg";
//create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
Toast.makeText(this, "picture has been taken"+ imageUri, Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
}
}
public static File convertImageUriToFile (Uri imageUri, Activity activity) {
Cursor cursor = null;
try {
String [] proj={MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
cursor = activity.managedQuery( imageUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// int orientation_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
if (cursor.moveToFirst()) {
// String orientation = cursor.getString(orientation_ColumnIndex);
return new File(cursor.getString(file_ColumnIndex));
}
return null;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
Mais dans ce code, l'appareil photo est ouvert et l'utilisateur doit cliquer sur le bouton pour prendre la photo. Ce que je veux, c'est prendre la photo automatiquement (sans aperçu) et la sauvegarder sur la carte mémoire.
Android ne vous permet pas de prendre des photos sans afficher la fenêtre d'aperçu. Il faut donc que la vue de la surface soit très petite. Comme 1 * 1 pixel et le mettre dans un coin de n'importe quel contrôle.
Ou montrez une vue factice de la surface pour le faire.
SurfaceView view = new SurfaceView(this);
c.setPreviewDisplay(view.getHolder());
c.startPreview();
c.takePicture(shutterCallback, rawPictureCallback, jpegPictureCallback);
Ce code capture une image à l'aide de la caméra avant et l'enregistre automatiquement
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
int index = getFrontCameraId();
if (index == -1){
Toast.makeText(getApplicationContext(), "No front camera", Toast.LENGTH_LONG).show();
}
else
{
iv_image = (ImageView) findViewById(R.id.imageView);
sv = (SurfaceView) findViewById(R.id.surfaceView);
sHolder = sv.getHolder();
sHolder.addCallback(this);
sHolder.setType(SurfaceHolder.SURFACE_TYPE_Push_BUFFERS);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
{
parameters = mCamera.getParameters();
mCamera.setParameters(parameters);
mCamera.startPreview();
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
@Override
public void onPictureTaken(byte[] data, Camera camera)
{
Uri uriTarget = getContentResolver().insert//(Media.EXTERNAL_CONTENT_URI, image);
(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(TakePictureActivity.this,
"Image saved: " + uriTarget.toString(), Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
//mCamera.startPreview();
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
iv_image.setImageBitmap(bmp);
}
};
mCamera.takePicture(null, null, mCall);
}
int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}
@Override
public void surfaceCreated(SurfaceHolder holder)
{
int index = getFrontCameraId();
if (index == -1){
Toast.makeText(getApplicationContext(), "No front camera", Toast.LENGTH_LONG).show();
}
else
{
mCamera = Camera.open(index);
Toast.makeText(getApplicationContext(), "With front camera", Toast.LENGTH_LONG).show();
}
mCamera = Camera.open(index);
try {
mCamera.setPreviewDisplay(holder);
} catch (IOException exception) {
mCamera.release();
mCamera = null;
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}
Capturing Image without user interaction(without user action) and capture an image in background using Android service
import Java.io.File;
import Java.io.FileNotFoundException;
import Java.io.FileOutputStream;
import Java.io.IOException;
import Java.text.SimpleDateFormat;
import Java.util.Calendar;
import Android.app.Service;
import Android.content.Intent;
import Android.hardware.Camera;
import Android.hardware.Camera.CameraInfo;
import Android.hardware.Camera.Parameters;
import Android.os.Environment;
import Android.os.IBinder;
import Android.os.StrictMode;
import Android.util.Log;
import Android.view.SurfaceHolder;
import Android.view.SurfaceView;
public class CapPhoto extends Service
{
private SurfaceHolder sHolder;
private Camera mCamera;
private Parameters parameters;
@Override
public void onCreate()
{
super.onCreate();
Log.d("CAM", "start");
if (Android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);};
Thread myThread = null;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if (Camera.getNumberOfCameras() >= 2) {
mCamera = Camera.open(CameraInfo.CAMERA_FACING_FRONT); }
if (Camera.getNumberOfCameras() < 2) {
mCamera = Camera.open(); }
SurfaceView sv = new SurfaceView(getApplicationContext());
try {
mCamera.setPreviewDisplay(sv.getHolder());
parameters = mCamera.getParameters();
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
} catch (IOException e) { e.printStackTrace(); }
sHolder = sv.getHolder();
sHolder.setType(SurfaceHolder.SURFACE_TYPE_Push_BUFFERS);
}
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(final byte[] data, Camera camera)
{
FileOutputStream outStream = null;
try{
File sd = new File(Environment.getExternalStorageDirectory(), "A");
if(!sd.exists()) {
sd.mkdirs();
Log.i("FO", "folder" + Environment.getExternalStorageDirectory());
}
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String tar = (sdf.format(cal.getTime()));
outStream = new FileOutputStream(sd+tar+".jpg");
outStream.write(data); outStream.close();
Log.i("CAM", data.length + " byte written to:"+sd+tar+".jpg");
camkapa(sHolder);
} catch (FileNotFoundException e){
Log.d("CAM", e.getMessage());
} catch (IOException e){
Log.d("CAM", e.getMessage());
}}
};
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void camkapa(SurfaceHolder sHolder) {
if (null == mCamera)
return;
mCamera.stopPreview();
mCamera.release();
mCamera = null;
Log.i("CAM", " closed");
}
}
Step:2 Activity File - name is :Second.Java
import Java.util.Calendar;
import Android.app.Activity;
import Android.app.AlarmManager;
import Android.app.PendingIntent;
import Android.content.Context;
import Android.content.Intent;
import Android.os.Bundle;
import Android.view.Menu;
public class Second extends Activity {
Intent service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Calendar cal = Calendar.getInstance();
service = new Intent(getBaseContext(), CapPhoto.class);
cal.add(Calendar.SECOND, 15);
//TAKE PHOTO EVERY 15 SECONDS
PendingIntent pintent = PendingIntent.getService(this, 0, service, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
60*60*1000, pintent);
startService(service);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
step 3: Android manife
st file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:Android="http://schemas.Android.com/apk/res/Android"
package="com.dbsource.dbinsert"
Android:versionCode="1"
Android:versionName="1.0" >
<uses-sdk
Android:minSdkVersion="8"
Android:targetSdkVersion="17" />
<uses-permission Android:name="Android.permission.CAMERA" />
<uses-permission Android:name="Android.permission.VIBRATE" />
<uses-permission Android:name="Android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission Android:name="Android.permission.ACCESS_FINE_LOCATION" />
<uses-permission Android:name="Android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission Android:name="Android.permission.READ_PHONE_STATE" />
<uses-permission Android:name="Android.permission.INTERNET" />
<uses-permission Android:name="Android.permission.RECEIVE_SMS" />
<uses-permission Android:name="Android.permission.RECORD_AUDIO" />
<uses-permission Android:name="Android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission Android:name="Android.permission.READ_CONTACTS" />
<uses-permission Android:name="Android.permission.WRITE_CONTACTS" />
<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission Android:name="Android.permission.ACCESS_NETWORK_STATE" />
<uses-permission Android:name="Android.permission.GET_ACCOUNTS" />
<uses-permission Android:name="Android.permission.BROADCAST_STICKY" />
<uses-permission Android:name="Android.permission.SEND_SMS" />
<uses-permission Android:name="Android.permission.READ_SMS" />
<uses-permission Android:name="Android.permission.READ_CONTACTS" />
<uses-permission Android:name="Android.permission.BROADCAST_STICKY" />
<uses-permission Android:name="Android.permission.WRITE_SETTINGS" />
<uses-feature Android:name="Android.hardware.camera" />
<application
Android:allowBackup="true"
Android:icon="@drawable/ic_launcher"
Android:label="@string/app_name" >
<activity
Android:name=".Second"
Android:label="@string/app_name" >
<intent-filter>
<action Android:name="Android.intent.action.MAIN" />
<category Android:name="Android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service Android:name=".CapPhoto" Android:enabled="true">
<intent-filter>
</intent-filter>
</service>
</application>
</manifest>
refer this link [enter link description here][1]
[1]: http://chandandroid.blogspot.in/2014/04/capturing-image-without-user-action.html
La description
Je voudrais prendre une photo avec le bouton sans confirmation sur Android.
Solution
Utilisez "Android.intent.extra.quickCapture"
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("Android.intent.extra.quickCapture",true);