Android abre la cámara desde el botón

Espero que esta no sea una pregunta duplicada, pero estoy creando una aplicación que quiere un botón para abrir la aplicación de la cámara (la cámara android predeterminada por separado). ¿Cómo tengo que hacer eso? Sé que hay una función:

intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE) 

¿Debo usar eso? ¿Y cómo llamo al botón del archivo xml?

Además, ¿debo preocuparme por almacenar esa imagen o video o la aplicación de cámara predeterminada se encargará de eso?

Para llamar a la cámara puede usar:

 Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivity(intent); 

La imagen se guardará automáticamente en un directorio predeterminado.

Y necesita establecer el permiso para la cámara en su AndroidManifest.xml:

   
  Button b = (Button)findViewById(R.id.Button01); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_PIC_REQUEST) { Bitmap image = (Bitmap) data.getExtras().get("data"); ImageView imageview = (ImageView) findViewById(R.id.ImageView01); //sets imageview as the bitmap imageview.setImageBitmap(image); } } 

Puede crear un bash de cámara y llamarlo como startActivityForResult (bash).

 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // start the image capture Intent startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); 

Sé que es un poco tarde para responder, pero puedes usar la syntax a continuación, ya que funcionó bien conmigo

 Camera=(Button)findViewById(R.id.CameraID); Camera.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent Intent3=new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA); startActivity(Intent3); } }); 

Para mí, esto funcionó perfectamente bien.

  Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivity(intent); 

y agrega este permiso al archivo mainfest:

  

Abre la cámara, después de capturar la imagen guarda la imagen en la galería con un nuevo conjunto de imágenes.

el siguiente código hace exactamente lo que quieres

// usar esta intención en el evento click

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent,CAMERA_REQUEST);

// el código anterior se usa en ‘en actividad Resultado’

 protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); if (requestCode == CAMERA_REQUEST) { Bitmap photo = (Bitmap) data.getExtras().get("data"); image.setImageBitmap(photo); } } 

Tiene razón sobre la acción utilizada en Intent, pero no es lo único que tiene que hacer. También deberás agregar

 startActivityForResult(intent, YOUR_REQUEST_CODE); 

Para hacer todo y recuperar la imagen real, puede consultar el siguiente hilo.

Android – Foto de captura

puedes usar el siguiente código

  Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); pic = new File(Environment.getExternalStorageDirectory(), mApp.getPreference().getString(Common.u_id, "") + ".jpg"); picUri = Uri.fromFile(pic); cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, picUri); cameraIntent.putExtra("return-data", true); startActivityForResult(cameraIntent, PHOTO); 

Creé un libray para elegir la imagen de la cámara o la galera y recortar también

Prueba esto,

ImagePro.Java

 public class ImagePro { public static String TAG = "ImagePro"; Activity activity; Uri mImageCaptureUri; public static int CAMERA_CODE = 64; public static int GALLERY_CODE = 74; public static int CROPPING_CODE = 84; private final static int REQUEST_PERMISSION_REQ_CODE = 704; public ImagePro(Activity activity) { this.activity = activity; this.outPutFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg"); if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE); } } private void LogToast(String message) { try { Toast.makeText(activity, message, Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } Log.d(TAG, message); } private void Toast(String message) { try { Toast.makeText(activity, message, Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } private void Log(String message) { Log.d(TAG, message); } /** * This function return captured image path * * @param requestCode on activity result requestCode * @param resultCode on activity result resultCode * @param intent on activity result intent * @return ImageDetails values */ public ImageDetails getImagePath(int requestCode, int resultCode, Intent intent) { ImageDetails imageDetails = new ImageDetails(); if(resultCode == Activity.RESULT_OK) { if(requestCode == CAMERA_CODE) { imageDetails.setUri(mImageCaptureUri); imageDetails.setPath(mImageCaptureUri.getPath()); Bitmap bitmap = null; try { bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), mImageCaptureUri); } catch (IOException e) { LogToast(e.getMessage()); e.printStackTrace(); } imageDetails.setBitmap(bitmap); imageDetails.setFile(new File(mImageCaptureUri.getPath())); } else if(requestCode == GALLERY_CODE) { Uri uri = intent.getData(); imageDetails.setUri(uri); Bitmap bitmap = null; try { bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri); } catch (IOException e) { LogToast(e.getMessage()); e.printStackTrace(); } imageDetails.setBitmap(bitmap); imageDetails.setFile(new File(uri.getPath())); imageDetails.setPath(uri.getPath()); } else if(requestCode == CROPPING_CODE) { try { if(outPutFile.exists()){ imageDetails.setUri(Uri.fromFile(outPutFile)); imageDetails.setFile(outPutFile); imageDetails.setPath(outPutFile.getPath()); Bitmap photo = decodeFile(outPutFile); imageDetails.setBitmap(photo); } else { LogToast("Error while save image"); } } catch (Exception e) { e.printStackTrace(); LogToast(e.getMessage()); } } } else { LogToast("user cancelled."); } return imageDetails; } /** * Open image pick dialog.
* CAMERA_CODE * GALLERY_CODE */ public void openImagePickOption() { final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" }; AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle("Add Photo!"); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int item) { if (items[item].equals("Capture Photo")) { captureImage(); } else if (items[item].equals("Choose from Gallery")) { pickImage(); } else if (items[item].equals("Cancel")) { dialog.dismiss(); } } }); builder.show(); } /** * decode from file to bitmap * @param f file * @return Bitmap data */ private Bitmap decodeFile(File f) { try { // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = 512; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) { Log(e.getMessage()); } return null; } /** * Capture image using camera
* REQUEST_CODE = ImagePro.CAMERA_CODE */ public void captureImage() { if(activity != null) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg"); mImageCaptureUri = Uri.fromFile(f); intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri); activity.startActivityForResult(intent, CAMERA_CODE); } else { LogToast("Activity not assigned"); } } /** * pick image from gallery */ public void pickImage() { Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); activity.startActivityForResult(i, GALLERY_CODE); } /** * cropping the uri image * @param uri - open cropping dialog using the uri data */ public void croppingImage(Uri uri) { CroppingIMG(uri); } int CROP_IMG_X=512; int CROP_IMG_Y=512; public void croppingImage(Uri uri, int cropX, int cropY) { CROP_IMG_X = cropX; CROP_IMG_Y = cropY; CroppingIMG(uri); } File outPutFile=null; private void CroppingIMG(Uri uri) { final ArrayList cropOptions = new ArrayList<>(); Intent intent = new Intent("com.android.camera.action.CROP"); intent.setType("image/*"); List list = activity.getPackageManager().queryIntentActivities( intent, 0 ); int size = list.size(); if (size == 0) { LogToast("Can't find image croping app"); } else { intent.setData(uri); intent.putExtra("outputX", CROP_IMG_X); intent.putExtra("outputY", CROP_IMG_Y); intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); intent.putExtra("scale", true); //Create output file here intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile)); if (size == 1) { Intent i = new Intent(intent); ResolveInfo res = list.get(0); i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); activity.startActivityForResult(i, CROPPING_CODE); } else { for (ResolveInfo res : list) { final CroppingOption co = new CroppingOption(); co.title = activity.getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo); co.icon = activity.getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo); co.appIntent = new Intent(intent); co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); cropOptions.add(co); } CropingOptionAdapter adapter = new CropingOptionAdapter(activity.getApplicationContext(), cropOptions); AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle("Choose Cropping App"); builder.setCancelable(false); builder.setAdapter( adapter, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int item ) { activity.startActivityForResult( cropOptions.get(item).appIntent, CROPPING_CODE); } }); builder.setOnCancelListener( new DialogInterface.OnCancelListener() { @Override public void onCancel( DialogInterface dialog ) { if (mImageCaptureUri != null ) { activity.getContentResolver().delete(mImageCaptureUri, null, null ); mImageCaptureUri = null; } } } ); AlertDialog alert = builder.create(); alert.show(); } } } /** * Capture image using camera
* REQUEST_CODE = User defined code
*
* @param iRequestCode User defined code */ public void captureImage(int iRequestCode) { CAMERA_CODE = iRequestCode; captureImage(); } /** * get path, bitmap, file and uri from image details object */ public class ImageDetails { String path=""; Bitmap bitmap=null; File file=null; Uri uri=null; public Uri getUri() { return uri; } public void setUri(Uri uri) { this.uri = uri; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Bitmap getBitmap() { return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } } /** * Created by DP on 7/12/2016. */ public class CroppingOption { public CharSequence title; public Drawable icon; public Intent appIntent; } public class CropingOptionAdapter extends ArrayAdapter { private ArrayList mOptions; private LayoutInflater mInflater; public CropingOptionAdapter(Context context, ArrayList options) { super(context, R.layout.croping_selector, options); mOptions = options; mInflater = LayoutInflater.from(context); } @Override public View getView(int position, View convertView, ViewGroup group) { if (convertView == null) convertView = mInflater.inflate(R.layout.croping_selector, null); CroppingOption item = mOptions.get(position); if (item != null) { ((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon); ((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title); return convertView; } return null; } } }

MainActivity.java

 ImagePro imagePro; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imagePro = new ImagePro(this); } public void onClickUploadImageButton(View view) { imagePro.openImagePickOption(); } 

onActivityResult

 if(requestCode == CAMERA_CODE && resultCode == RESULT_OK) { imageDetails = imagePro.getImagePath(CAMERA_CODE, RESULT_OK, data); ivCrop.setImageBitmap(imageDetails.getBitmap()); //imageDetails.getPath(), imageDetails.getBitmap(), imageDetails.getUri(), imageDetails.getFile } 
  private static final int CAMERA_CAPTURE = 1; private Uri fileUri; btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { capturepic(); } }); private void capturepic() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(intent, CAMERA_CAPTURE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if the result is capturing Image if (requestCode == CAMERA_CAPTURE) { if (resultCode == RESULT_OK) { capturedImage(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(Activity.this, "User cancelled image capture", Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(Activity.this, "Failed to capture image", Toast.LENGTH_SHORT) .show(); } } } private void capturedImage() { try { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options); img.setImageBitmap(bitmap); } catch (NullPointerException e) { e.printStackTrace(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable("file_uri", fileUri); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); fileUri = savedInstanceState.getParcelable("file_uri"); } 

Espero eso ayude.