2015-09-01 15 views
5

Devo avviare la fotocamera, e quando gli utenti hanno fatto l'immagine, devo prenderla e mostrarla in una vista.Come ottenere il percorso dell'immagine in onActivityresult (I dati di intenti sono nulli)

Guardando http://developer.android.com/guide/topics/media/camera.html ho fatto:

protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     bLaunchCamera = (Button) findViewById(R.id.launchCamera); 
     bLaunchCamera.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Log.d(TAG, "lanzando camara"); 

       //create intent to launch camera 
       Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 

       imageUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); //create a file to save the image 
       intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); //set the image file name 

       //start camera 
       startActivityForResult(intent, CAMERA_REQUEST); 
      } 
     }); 

/** 
    * Create a File Uri for saving image (can be sued to save video to) 
    **/ 
    private Uri getOutputMediaFileUri(int mediaTypeImage) { 
     return Uri.fromFile(getOutputMediaFile(mediaTypeImage)); 
    } 

    /** 
    * Create a File for saving image (can be sued to save video to) 
    **/ 
    private File getOutputMediaFile(int mediaType) { 
     //To be safe, is necessary to check if SDCard is mounted 

     File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), 
       (String) getResources().getText(R.string.app_name)); 

     //create the storage directory if it does not exist 
     if (!mediaStorageDir.exists()) { 
      if (!mediaStorageDir.mkdirs()) { 
       Log.d(TAG, "failed to create directory"); 
       return null; 
      } 
     } 

     //Create a media file name 

     String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date()); 
     File mediaFile; 

     if (mediaType == MEDIA_TYPE_IMAGE) { 
      mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"); 

     } else { 
      return null; 
     } 
     return mediaFile; 
    } 

@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if(requestCode == CAMERA_REQUEST) { 
      if(resultCode == RESULT_OK) { 
       //Image captured and saved to fileUri specified in Intent 
       Toast.makeText(this, "image saved to:\n" + data.getData(), Toast.LENGTH_LONG).show(); 
       Log.d(TAG, "lanzando camara"); 
      } else if(resultCode == RESULT_CANCELED) { 
       //user cancelled the image capture; 
       Log.d(TAG, "usuario a cancelado la captura"); 
      } else { 
       //image capture failed, advise user; 
       Log.d(TAG, "algo a fallado"); 
      } 
     } 
    } 

Quando l'immagine è stato fatto, l'applicazione si blocca quando si tenta di inviare informazioni 'Toast' perche 'i dati' è nullo.

Ma se eseguo il debug dell'applicazione, posso vedere che l'immagine è stata salvata.

enter image description here

Quindi la mia domanda è: come posso ottenere il percorso nel onActivityResult?

risposta

2

Questo è il codice che ho usato per acquisire e salvare l'immagine della telecamera, quindi visualizzarlo su imageview. Puoi usare secondo le tue necessità.

È necessario salvare l'immagine della telecamera in una posizione specifica, quindi recuperare da tale posizione e quindi convertirla in array di byte.

Ecco il metodo per aprire l'acquisizione dell'attività dell'immagine della telecamera.

private static final int CAMERA_PHOTO = 111; 
private Uri imageToUploadUri; 

private void captureCameraImage() { 
     Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg"); 
     chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
     imageToUploadUri = Uri.fromFile(f); 
     startActivityForResult(chooserIntent, CAMERA_PHOTO); 
    } 

@Override 
     protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
      super.onActivityResult(requestCode, resultCode, data); 

      if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) { 
       if(imageToUploadUri != null){ 
        Uri selectedImage = imageToUploadUri; 
        getContentResolver().notifyChange(selectedImage, null); 
        Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath()); 
        if(reducedSizeBitmap != null){ 
         ImgPhoto.setImageBitmap(reducedSizeBitmap); 
         Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton); 
          uploadImageButton.setVisibility(View.VISIBLE);     
        }else{ 
         Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show(); 
        } 
       }else{ 
        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show(); 
       } 
      } 
     } 

Ecco il metodo getBitmap() utilizzato in onActivityResult(). Ho fatto tutto il miglioramento delle prestazioni che è possibile ottenere durante l'acquisizione di immagini bitmap.

private Bitmap getBitmap(String path) { 

     Uri uri = Uri.fromFile(new File(path)); 
     InputStream in = null; 
     try { 
      final int IMAGE_MAX_SIZE = 1200000; // 1.2MP 
      in = getContentResolver().openInputStream(uri); 

      // Decode image size 
      BitmapFactory.Options o = new BitmapFactory.Options(); 
      o.inJustDecodeBounds = true; 
      BitmapFactory.decodeStream(in, null, o); 
      in.close(); 


      int scale = 1; 
      while ((o.outWidth * o.outHeight) * (1/Math.pow(scale, 2)) > 
        IMAGE_MAX_SIZE) { 
       scale++; 
      } 
      Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight); 

      Bitmap b = null; 
      in = getContentResolver().openInputStream(uri); 
      if (scale > 1) { 
       scale--; 
       // scale to max possible inSampleSize that still yields an image 
       // larger than target 
       o = new BitmapFactory.Options(); 
       o.inSampleSize = scale; 
       b = BitmapFactory.decodeStream(in, null, o); 

       // resize to desired dimensions 
       int height = b.getHeight(); 
       int width = b.getWidth(); 
       Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height); 

       double y = Math.sqrt(IMAGE_MAX_SIZE 
         /(((double) width)/height)); 
       double x = (y/height) * width; 

       Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x, 
         (int) y, true); 
       b.recycle(); 
       b = scaledBitmap; 

       System.gc(); 
      } else { 
       b = BitmapFactory.decodeStream(in); 
      } 
      in.close(); 

      Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " + 
        b.getHeight()); 
      return b; 
     } catch (IOException e) { 
      Log.e("", e.getMessage(), e); 
      return null; 
     } 
    } 

Spero che sia d'aiuto!

+0

Sì! trovato la soluzione al mio problema in questa riga -> if (imageToUploadUri! = null) { Uri selectedImage = imageToUploadUri; Molte grazie! – Shudy

2

Amigo,

Il problema che si trovano ad affrontare è che, ogni volta che selezioniamo un'immagine dalla intento fotocamera, potrebbe finire l'attività che ha chiamato, quindi imageUri oggetto creato sarà nullo mentre si torna.

quindi è necessario salvarlo quando si esce l'attività (per andare a dolo macchina fotografica), come questo -

/** 
    * Here we store the file url as it will be null after returning from camera 
    * app 
    */ 
    @Override 
    protected void onSaveInstanceState(Bundle outState) { 
     super.onSaveInstanceState(outState); 

     // save file url in bundle as it will be null on screen orientation 
     // changes 
     outState.putParcelable("file_uri", mImageUri); 
    } 

e recuperare indietro quando si torna all'attività -

@Override 
    protected void onRestoreInstanceState(Bundle savedInstanceState) { 
     super.onRestoreInstanceState(savedInstanceState); 

     // get the file url 
     mImageUri = savedInstanceState.getParcelable("file_uri"); 
    } 

Il tuo codice sembra buono, devi solo aggiungere questa modifica.

Problemi correlati