"Tomar una foto y presentarla" en modo retrato en Samsung Galaxy S
Estoy tratando de simplemente tomar una foto y presentarla en un ImageView con mi samsung galaxy s. Está funcionando bien cuando lo hago en el paisaje, pero no en el retrato. No estoy recibiendo ningún error o excepción – simplemente no conseguir nada … Hay un montón de preguntas sobre este tema y parece ser problemático (algo sobre la orientación de la cámara), pero counldn't averiguar la solución final para un simple " Tomar una foto y presentarla "código. Aquí está mi código (problemático) que no funciona:
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"); }
}
- Acceder a la cámara frontal y posterior simultáneamente en los dispositivos Samsung Galaxy
- Ancho más pequeño para Galaxy S y Galaxy S2
- Cómo ver la consola Javascript de Stock Browser en Android Galaxy S4
- USB Accessory API en el Samsung Galaxy S2 Android
- Samsung Galaxy / Holoeverywhere - El recurso no es un ColorStateList (color o ruta)
Sólo necesito un código que funcione (en cualquier dispositivo) o una corrección a mi código … thx.
- PhoneGap y Galaxy s4 procesan problema
- API de impresión de Android en la pestaña Galaxy
- Enviar SMS a través de ADB al teléfono
- Eclipse y Android: no se puede depurar en Samsung Galaxy S2 porque no se ha detectado
- Aplicación de Android Studio en ejecución en el Samsung Galaxy S3 se bloquea al subir el archivo
- El diálogo "Make Bug Report" de Galaxy S4 nunca se inicializa
- Excepción de puntero nulo en la ventana de sugerencias popup en Samsung Galaxy Android 7
- Configuración del emulador Samsung Galaxy s3
La razón por la que se llama onCreate()
es porque cuando llamas a la actividad de la cámara durante la orientación vertical, cambiará la orientación y destruirá tu actividad anterior. Después de terminar el onActivityResult()
, su actividad se volverá a crear.
Una solución a este problema es configurar el manifiesto para ignorar los cambios en el cambio de orientación, puede hacerlo utilizando esto:
<activity android:name=".MyMainActivity" android:configChanges="orientation" android:label="@string/app_name" />
Si está utilizando la API comienza con el nivel 13, puede considerar screenSize
para el manifiesto configChanges.
Sólo puedo sugerir un hack para este problema. Guarde los resultados en las preferencias compartidas en onActivityResult()
y durante onCreate
cargue su contenido desde preferencias compartidas. Sé que esta es una mala solución, pero esto te mantendrá hasta que encuentres una mejor respuesta. Y no olvide borrar sus preferencias compartidas una vez que haya terminado, de lo contrario su actividad siempre se inicializará con datos antiguos.
Prueba el siguiente código .. funcionó para mí 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(); }
Es fácil detectar la orientación de la imagen y reemplazar el mapa de bits mediante:
/** * 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 la pérdida de recuerdos con imágenes grandes, te recomiendo que cambies 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 utilizar ExifInterface para obtener la orientación debido a un problema de Android OS: https://code.google.com/p/android/issues/detail?id=19268
- Android: Cómo obtener un mapa OSM girado para llenar la pantalla completa
- Google App Engine – escala automática con siempre en instancia?