2009-12-29 19 views
22

Estoy intentando recortar una imagen después de tomarla, y mi código es el siguiente:Android: recortar una imagen después de tomarla con la cámara con un aspecto fija Relación de

private void doTakePhotoAction() { 

     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     intent.putExtra(MediaStore.EXTRA_OUTPUT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString()); 
     intent.putExtra("crop", "true"); 
     intent.putExtra("aspectX", 1); 
     intent.putExtra("aspectY", 1); 
     intent.putExtra("outputX", 96); 
     intent.putExtra("outputY", 96); 

     try { 
      intent.putExtra("return-data", true); 
      startActivityForResult(intent, PICK_FROM_CAMERA); 
     } catch (ActivityNotFoundException e) { 
      //Do nothing for now 
     } 
    } 

Con el código anterior, me Puedo ir al modo de recorte y recortar la imagen. Sin embargo, la relación de aspecto 1: 1 no se aplica, y tampoco la salidaX y la salidaY. Creo que esto se debe a que la intención era tomar una fotografía, no para recortar. También he escrito otro método para getData() de la Intención, y después de eso usa la siguiente:

Intent intent = new Intent("com.android.camera.action.CROP"); 
intent.setClassName("com.android.camera", "com.android.camera.CropImage"); 

Sin embargo, cuando lo hago, me sale el siguiente error de ejecución:

E/AndroidRuntime(14648): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.camera/com.android.camera.CropImage}: java.lang.NullPointerException 

¡Gracias por la ayuda! :)

Respuesta

2

¿Has probado este Intent (pero manteniendo los extras de recorte/aspecto/salida/devolución de datos que ya tienes)?

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
intent.setType("image/*"); 

Eso es básicamente lo que el Android contacts application hace, así que tal vez no exactamente a su caso de uso (es decir, tomar una foto de inmediato, en lugar de tener la opción de seleccionar uno de la galería o tomar una nueva foto)

¡De todos modos, vale la pena intentarlo! :)

+0

No funciona ni para mí: android.content.ActivityNotFoundException: No se ha encontrado actividad para manejar el intento {act = android.intent.action.GET_CONTENT (tiene extras)} – stoefln

22

Después de leer un poco, me di cuenta de que no se puede hacer así de simple. Mi fuente modificada de contactos está en http://github.com/Wysie, puede ver si está interesado. Además, aquí es lo que hice para que funcione:

private void doTakePhotoAction() { 
    // http://2009.hfoss.org/Tutorial:Camera_and_Gallery_Demo 
    // http://stackoverflow.com/questions/1050297/how-to-get-the-url-of-the-captured-image 
    // http://www.damonkohler.com/2009/02/android-recipes.html 
    // http://www.firstclown.us/tag/android/ 
    // The one I used to get everything working: http://groups.google.com/group/android-developers/msg/2ab62c12ee99ba30 

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

    //Wysie_Soh: Create path for temp file 
    mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), 
         "tmp_contact_" + String.valueOf(System.currentTimeMillis()) + ".jpg")); 

    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); 

    try { 
     intent.putExtra("return-data", true); 
     startActivityForResult(intent, PICK_FROM_CAMERA); 
    } catch (ActivityNotFoundException e) { 
     //Do nothing for now 
    } 
} 

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    if (resultCode != RESULT_OK) { 
     return; 
    } 

    switch (requestCode) { 

    case CROP_FROM_CAMERA: { 
     //Wysie_Soh: After a picture is taken, it will go to PICK_FROM_CAMERA, which will then come here 
     //after the image is cropped. 

     final Bundle extras = data.getExtras(); 

     if (extras != null) { 
      Bitmap photo = extras.getParcelable("data"); 

      mPhoto = photo; 
      mPhotoChanged = true; 
      mPhotoImageView.setImageBitmap(photo); 
      setPhotoPresent(true); 
     } 

     //Wysie_Soh: Delete the temporary file       
     File f = new File(mImageCaptureUri.getPath());    
     if (f.exists()) { 
      f.delete(); 
     } 

     InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 
     mgr.showSoftInput(mPhotoImageView, InputMethodManager.SHOW_IMPLICIT); 

     break; 
    } 

    case PICK_FROM_CAMERA: { 
     //Wysie_Soh: After an image is taken and saved to the location of mImageCaptureUri, come here 
     //and load the crop editor, with the necessary parameters (96x96, 1:1 ratio) 

     Intent intent = new Intent("com.android.camera.action.CROP"); 
     intent.setClassName("com.android.camera", "com.android.camera.CropImage"); 

     intent.setData(mImageCaptureUri); 
     intent.putExtra("outputX", 96); 
     intent.putExtra("outputY", 96); 
     intent.putExtra("aspectX", 1); 
     intent.putExtra("aspectY", 1); 
     intent.putExtra("scale", true); 
     intent.putExtra("return-data", true);    
     startActivityForResult(intent, CROP_FROM_CAMERA); 

     break; 

    } 
    } 
} 

espero que ayude :)

+0

¡increíble! ¡Gracias! –

+16

Gracias Wysie, pero no funciona en Android 2.x. Esta es la excepción: 04-29 18: 35: 02.857: ERROR/AndroidRuntime (3486): Causado por: android.content.ActivityNotFoundException: no se puede encontrar la clase de actividad explícita {com.android.camera/com.android.camera .Delimitar imagen}; ¿Has declarado esta actividad en tu AndroidManifest.xml? –

+0

si outputX es más de 500 entonces ¿no funciona alguna idea? – somish

-3

Aunque esto podría ser un hilo muy antiguo, que fue capaz de recortar una imagen mediante programación con el siguiente código:

 btnTakePicture.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Intent cameraIntent = new Intent(
        android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 

      startActivityForResult(cameraIntent, CAMERA_REQUEST); 
     } 
    }); 

luego recortada con:

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 

    if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) { 

     photo = (Bitmap) data.getExtras().get("data"); 

     performcrop(); 
    } 

} 

private void performcrop() { 
    DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics(); 
    int width = displayMetrics.widthPixels; 
    int height = displayMetrics.heightPixels; 

    Bitmap croppedBmp = Bitmap.createBitmap(photo, 0, 0, width/2, 
      photo.getHeight()); 

    imageTaken.setImageBitmap(croppedBmp); 
} 

imageTaken es un componente de ImageView en mi opinión. Puedes ver mi fuente Here

Cuestiones relacionadas