2012-09-01 20 views
8

Estoy tratando de simplemente tomar una foto y presentarla en una ImageView con mis samsung galaxy s. Está funcionando bien cuando lo hago en el paisaje, pero no en el retrato. No recibo ningún error o excepción, simplemente no obtengo nada ... Hay muchas preguntas sobre este tema y parece ser problemático (algo sobre la orientación de la cámara), pero no encontré la solución final para un simple " toma una foto y preséntala "código. aquí es mi (problemática) de código que no funciona:"tomar una foto y presentarla" en modo retrato en Samsung Galaxy S

private void setUpListeners() { 
    takePicture.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View arg0) { 
      Intent cameraIntent = new Intent(
        android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
      startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); 
     } 
    }); 
} 

protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode == RESULT_OK) { 
     if (requestCode == CAMERA_PIC_REQUEST) { 
      Log.d("onActivityResult", "CAMERA_PIC_REQUEST returned"); 
      dishImage = (Bitmap) data.getExtras().get("data"); 
      if (dishImage==null) 
       Log.d("onActivityResult", "dishImage==null"); 
      imageView = (ImageView) findViewById(R.id.dishinfodishimageview); 
      imageView.setImageBitmap(dishImage); 
      imageView.setVisibility(View.VISIBLE); 
      takePicture.setVisibility(View.GONE); 
      (new UploadImage()).execute(null); 
     } 
    } else { 
     Log.e("onActivityResult", 
       "no able to presenting the picture of the dish"); 
    } 

}

Sólo necesito un código que funciona (en cualquier dispositivo) o una solución a mi código ... THX.

+0

vea este antiguo [respuesta] (http://stackoverflow.com/a/11084765/1250370). Puede ser que te ayude. :) – Deepak

+0

para rotar su imagen de mapa de bits consulte este [enlace] (http://stackoverflow.com/a/6051340/1250370) – Deepak

+0

Todavía no lo entiendo: en orientación vertical no obtengo una imagen girada. ..No obtengo una imagen en absoluto ... y no es un error o excepción ... parece que se está saltando la línea imageView.setImageBitmap (dishImage); (pero en el paisaje está funcionando ...) – yehudahs

Respuesta

1

Solo puedo sugerir un truco para este problema. Guarde los resultados en las preferencias compartidas en onActivityResult() y durante onCreate cargue su contenido de las preferencias compartidas. Sé que esta es una mala solución, pero esto te mantendrá activo hasta que encuentres una mejor respuesta. Y no se olvide de borrar sus preferencias compartidas una vez que haya terminado, de lo contrario, su actividad siempre se inicializará con datos antiguos.

2

La razón por la que se llama al onCreate() se debe a que cuando llama a la actividad de la cámara durante la orientación vertical, cambiará la orientación y destruirá su actividad anterior. Después de terminar el onActivityResult(), su actividad se volverá a crear.

Una solución a este problema es establecer el manifiesto para ignorar los cambios en el cambio de orientación, puede hacerlo a través de este:

<activity android:name=".MyMainActivity" 
    android:configChanges="orientation" 
    android:label="@string/app_name" /> 

Si está utilizando la API se inicia con el nivel 13, se puede considerar screenSize para el manifiesto configChanges.

1

Pruebe el siguiente código .. a mí me funcionó con Samsung Galaxy S2 Inserte el siguiente código en onActivityResult()

ExifInterface exif = new ExifInterface(cameraimagename); 
        String orientString = exif.getAttribute(ExifInterface.TAG_ORIENTATION); 
        int orientation = orientString != null ? Integer.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL; 
        int rotationAngle = 0; 
        System.out.println("orientation is : "+orientation); 
        System.out.println("ExifInterface.ORIENTATION_ROTATE_90 : "+ExifInterface.ORIENTATION_ROTATE_90); 
        System.out.println("ExifInterface.ORIENTATION_ROTATE_180 : "+ExifInterface.ORIENTATION_ROTATE_180); 
        System.out.println("ExifInterface.ORIENTATION_ROTATE_270 : "+ExifInterface.ORIENTATION_ROTATE_270); 

        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) rotationAngle = 90; 
        if (orientation == ExifInterface.ORIENTATION_ROTATE_180) rotationAngle = 180; 
        if (orientation == ExifInterface.ORIENTATION_ROTATE_270) rotationAngle = 270; 
        System.out.println("Rotation Angle is : "+rotationAngle); 
        Matrix matrix = new Matrix(); 
        // matrix.setRotate(rotationAngle, (float) photo.getWidth()/2, (float) photo.getHeight()/2); 
        matrix.postRotate(rotationAngle); 

        Bitmap rotatedBitmap=null; 
        try { 
         rotatedBitmap = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true); 
        } catch (Exception e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
+0

cameraimagename = ruta de acceso de la imagen (String) y Photo es el objeto de mapa de bits generado anteriormente –

+0

Intenté un código similar, me ha resultado muy lento, ¿experimenta el mismo problema? –

+0

No @Helin Wang funciona perfectamente en mi dispositivo Galaxy S2 –

0

Es fácil detectar la orientación de la imagen y vuelva a colocar el mapa de bits usando:

/** 
* Rotate an image if required. 
* @param img 
* @param selectedImage 
* @return 
*/ 
private static Bitmap rotateImageIfRequired(Context context,Bitmap img, Uri selectedImage) { 

    // Detect rotation 
    int rotation=getRotation(context, selectedImage); 
    if(rotation!=0){ 
     Matrix matrix = new Matrix(); 
     matrix.postRotate(rotation); 
     Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true); 
     img.recycle(); 
     return rotatedImg;   
    }else{ 
     return img; 
    } 
} 

/** 
* Get the rotation of the last image added. 
* @param context 
* @param selectedImage 
* @return 
*/ 
private static int getRotation(Context context,Uri selectedImage) { 
    int rotation =0; 
    ContentResolver content = context.getContentResolver(); 


    Cursor mediaCursor = content.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
      new String[] { "orientation", "date_added" },null, null,"date_added desc"); 

    if (mediaCursor != null && mediaCursor.getCount() !=0) { 
     while(mediaCursor.moveToNext()){ 
      rotation = mediaCursor.getInt(0); 
      break; 
     } 
    } 
    mediaCursor.close(); 
    return rotation; 
} 

para evitar Fuera de recuerdos con imágenes grandes, me gustaría recomendar que al cambiar la escala de la imagen usando:

private static final int MAX_HEIGHT = 1024; 
private static final int MAX_WIDTH = 1024; 
public static Bitmap decodeSampledBitmap(Context context, Uri selectedImage) 
     throws IOException { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    InputStream imageStream = context.getContentResolver().openInputStream(selectedImage); 
    BitmapFactory.decodeStream(imageStream, null, options); 
    imageStream.close(); 

    // Calculate inSampleSize 
    options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT); 

    // Decode bitmap with inSampleSize set 
    options.inJustDecodeBounds = false; 
    imageStream = context.getContentResolver().openInputStream(selectedImage); 
    Bitmap img = BitmapFactory.decodeStream(imageStream, null, options); 

    img= rotateImageIfRequired(img, selectedImage); 
    return img; 
} 

No es posible usar ExifInterface para obtener la orientación debido a un problema con el sistema operativo Android: https://code.google.com/p/android/issues/detail?id=19268

Cuestiones relacionadas