2016-04-06 4 views
1

Le code de l'application ci-dessous qui im ​​travaille montre une boîte de dialogue où je peux choisir de prendre une photo ou de choisir une image dans une galerie.Voici le code de la caméra fonctionne très bien quand il s'agit de la sélection d'images de la galerie, il n'affiche pas l'image sur ma vue de l'image que j'ai sélectionnée. S'il vous plaît essayer de me dégager de cet obstacle? `Sélection d'images à partir de Galerie et prendre des photos dans Android App

MainActivity.java

public class MainActivity extends Activity { 

ImageView viewImage; 
Button b; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    b=(Button)findViewById(R.id.btnSelectPhoto); 
    viewImage=(ImageView)findViewById(R.id.viewImage); 
    b.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      selectImage(); 
     } 
    }); 
} 


private void selectImage() { 

    final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" }; 

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
    builder.setTitle("Add Photo!"); 
    builder.setItems(options, new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int item) { 
      if (options[item].equals("Take Photo")) 
      { 
       Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg"); 
       intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); 
       startActivityForResult(intent, 1); 
      } 
      else if (options[item].equals("Choose from Gallery")) 
      { 
       Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
       startActivityForResult(intent, 2); 

      } 
      else if (options[item].equals("Cancel")) { 
       dialog.dismiss(); 
      } 
     } 
    }); 
    builder.show(); 
} 

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if (resultCode == RESULT_OK) { 
     if (requestCode == 1) { 
      File f = new File(Environment.getExternalStorageDirectory().toString()); 
      for (File temp : f.listFiles()) { 
       if (temp.getName().equals("temp.jpg")) { 
        f = temp; 
        break; 
       } 
      } 
      try { 
       Bitmap bitmap; 
       BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); 

       bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), 
         bitmapOptions); 

       viewImage.setImageBitmap(bitmap); 

       String path = android.os.Environment 
         .getExternalStorageDirectory() 
         + File.separator 
         + "Phoenix" + File.separator + "default"; 
       f.delete(); 
       OutputStream outFile = null; 
       File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg"); 
       try { 
        outFile = new FileOutputStream(file); 
        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile); 
        outFile.flush(); 
        outFile.close(); 
       } catch (FileNotFoundException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } else if (requestCode == 2) { 

      Uri selectedImage = data.getData(); 
      String[] filePath = { MediaStore.Images.Media.DATA }; 
      Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null); 
      c.moveToFirst(); 
      int columnIndex = c.getColumnIndex(filePath[0]); 
      String picturePath = c.getString(columnIndex); 
      c.close(); 
      Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath)); 
      Log.w("path of image from gallery......******************.........", picturePath+""); 
      viewImage.setImageBitmap(thumbnail); 
     } 
    } 
} 

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 

android:id="@+id/LinearLayout1" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
android:padding="10dp" > 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    android:padding="5dp" > 

    <Button 
     android:id="@+id/btnSelectPhoto" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Select Photo" /> 

</LinearLayout> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:padding="10dp" > 

    <ImageView 
     android:id="@+id/viewImage" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:src="@drawable/camera" /> 

</LinearLayout> 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.example.venka.camox"> 
<uses-permission android:name="android.permission.CAMERA" /> 
<uses-feature android:name="android.hardware.camera" /> 
<uses-feature android:name="android.hardware.camera.autofocus" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 


<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

+1

double possible http: // stackoverflow. com/questions/35616916/création d'un fichier-de-picking-une-image-de-mediastore-action-image-capture/35617131 # 35617131 – ELITE

Répondre

0

changement autre code partiel dans votre méthode onActivityResult à ce qui suit

} else if (requestCode == 2) { 
    Uri selectedImage = data.getData(); 
    //String[] filePath = { MediaStore.Images.Media.DATA }; 
    //Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null); 
    //c.moveToFirst(); 
    //int columnIndex = c.getColumnIndex(filePath[0]); 
    String picturePath = getPath(this, selectedImage); 
    //c.close(); 
    Bitmap thumbnail = BitmapFactory.decodeFile(picturePath); 
    Log.w("path of image from gallery......******************.........", picturePath+""); 
    viewImage.setImageBitmap(thumbnail); 
} 

Et ajoutez ci-dessous le code pour obtenir le chemin réel de Uri

/** 
* Get a file path from a Uri. This will get the the path for Storage Access 
* Framework Documents, as well as the _data field for the MediaStore and 
* other file-based ContentProviders. 
* 
* @param context The context. 
* @param uri The Uri to query. 
* @author rahul 
*/ 
public static String getPath(final Context context, final Uri uri) { 

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; 

    // DocumentProvider 
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { 
     // ExternalStorageProvider 
     if (isExternalStorageDocument(uri)) { 
      final String docId = DocumentsContract.getDocumentId(uri); 
      final String[] split = docId.split(":"); 
      final String type = split[0]; 

      if ("primary".equalsIgnoreCase(type)) { 
       return Environment.getExternalStorageDirectory() + "/" + split[1]; 
      } 

      // TODO handle non-primary volumes 
     } 
     // DownloadsProvider 
     else if (isDownloadsDocument(uri)) { 

      final String id = DocumentsContract.getDocumentId(uri); 
      final Uri contentUri = ContentUris.withAppendedId(
        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); 

      return getDataColumn(context, contentUri, null, null); 
     } 
     // MediaProvider 
     else if (isMediaDocument(uri)) { 
      final String docId = DocumentsContract.getDocumentId(uri); 
      final String[] split = docId.split(":"); 
      final String type = split[0]; 

      Uri contentUri = null; 
      if ("image".equals(type)) { 
       contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; 
      } else if ("video".equals(type)) { 
       contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; 
      } else if ("audio".equals(type)) { 
       contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
      } 

      final String selection = "_id=?"; 
      final String[] selectionArgs = new String[] { 
        split[1] 
      }; 

      return getDataColumn(context, contentUri, selection, selectionArgs); 
     } 
    } 
    // MediaStore (and general) 
    else if ("content".equalsIgnoreCase(uri.getScheme())) { 

     // Return the remote address 
     if (isGooglePhotosUri(uri)) 
      return uri.getLastPathSegment(); 

     return getDataColumn(context, uri, null, null); 
    } 
    // File 
    else if ("file".equalsIgnoreCase(uri.getScheme())) { 
     return uri.getPath(); 
    } 

    return null; 
} 

/** 
* Get the value of the data column for this Uri. This is useful for 
* MediaStore Uris, and other file-based ContentProviders. 
* 
* @param context The context. 
* @param uri The Uri to query. 
* @param selection (Optional) Filter used in the query. 
* @param selectionArgs (Optional) Selection arguments used in the query. 
* @return The value of the _data column, which is typically a file path. 
*/ 
public static String getDataColumn(Context context, Uri uri, String selection, 
     String[] selectionArgs) { 

    Cursor cursor = null; 
    final String column = "_data"; 
    final String[] projection = { 
      column 
    }; 

    try { 
     cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, 
       null); 
     if (cursor != null && cursor.moveToFirst()) { 
      final int index = cursor.getColumnIndexOrThrow(column); 
      return cursor.getString(index); 
     } 
    } finally { 
     if (cursor != null) 
      cursor.close(); 
    } 
    return null; 
} 


/** 
* @param uri The Uri to check. 
* @return Whether the Uri authority is ExternalStorageProvider. 
*/ 
public static boolean isExternalStorageDocument(Uri uri) { 
    return "com.android.externalstorage.documents".equals(uri.getAuthority()); 
} 

/** 
* @param uri The Uri to check. 
* @return Whether the Uri authority is DownloadsProvider. 
*/ 
public static boolean isDownloadsDocument(Uri uri) { 
    return "com.android.providers.downloads.documents".equals(uri.getAuthority()); 
} 

/** 
* @param uri The Uri to check. 
* @return Whether the Uri authority is MediaProvider. 
*/ 
public static boolean isMediaDocument(Uri uri) { 
    return "com.android.providers.media.documents".equals(uri.getAuthority()); 
} 

/** 
* @param uri The Uri to check. 
* @return Whether the Uri authority is Google Photos. 
*/ 
public static boolean isGooglePhotosUri(Uri uri) { 
    return "com.google.android.apps.photos.content".equals(uri.getAuthority()); 
} 
+0

J'ai copié votre code nd essayé, mais il me donne 50errors Erreur: (149, 19) erreur: classe, interface, ou enum attendu (tous les mêmes). Et je n'ai aucune idée de l'endroit où les corriger. Mais si je supprime les mots clés 'final' du type String les erreurs décrémentent mais je ne peux pas trouver le moyen de rectifier d'autres erreurs. –

+0

Sur quelle ligne il se produit – ELITE

+0

les erreurs se produisent dans le code u metioned "pour obtenir le chemin d'accès réel de l'URI" ... –