2016-04-06 9 views
1

Üzerinde çalıştığım aşağıdaki uygulama kodu, fotoğraf çekmeyi veya galeriden bir resim seçmeyi seçebileceğim bir iletişim kutusu gösterir. Kamera kodu düzgün çalışır ancak Galeriden görüntü seçimi söz konusu olduğunda, görüntüyü, seçtiğim resim görünümümde görüntülemez. Bu engel beni temizlemek için deneyin? `Galeriden görüntü seçimi ve fotoğrafını Android Uygulamasında alma

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

olası yinelenen http gerçek yolunu almak için: // stackoverflow. com/questions/35616916/create-a-file-from-pick-an-image-from-mediastore-eylem-görüntü-yakalama/35617131 # 35617131 Kodunuzu kopyaladım bir – ELITE

cevap

0

aşağıdaki

} 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); 
} 

için onActivityResult yönteminde değişiklik başka parçası kod Ve kodunun altına ekleyin 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

nd çalıştı ama bana 50errors hatası veriyor: (149, 19) hatası: sınıf, arabirim veya enum bekleniyor (tümü aynı). Ve onları düzeltecekleri konusunda hiçbir fikrim yok. Ancak 'final' anahtar kelimelerini kaldırırsam, Type string decrement dize ama diğer hataları nasıl düzelteceğimi bulamıyorum. –

+0

Hangi satırda – ELITE

+0

oluşur hata "URI gerçek yol almak için" metioned metrede oluşur " –

İlgili konular