0

我已經實現了從SD或相機選擇圖像的代碼。 但是,我的圖像不出現在ImageView,我無法從SD卡中選擇圖像。Android選擇圖片或照相機

當我點擊SD卡上的圖片時,它會立即跳回到我的活動。

final String[] items = new String[] {"From Camera","From SD Card"}; 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_item,items); 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setTitle("Select Image"); 
    builder.setAdapter(adapter,new DialogInterface.OnClickListener(){ 
     public void onClick(DialogInterface dialog,int which){ 
      if(which == 0){ 
       intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       File file = new File(Environment.getExternalStorageDirectory(),"event_image"+String.valueOf(System.currentTimeMillis()+".jpg")); 
       imageCaptureUri = Uri.fromFile(file); 
       try { 
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageCaptureUri); 
        intent.putExtra("return data",true); 
        startActivityForResult(intent,PICK_FROM_CAMERA); 
       }catch(Exception ex){ 
        ex.printStackTrace(); 
       } 
       dialog.cancel(); 
      }else{ 
       intent = new Intent(); 
       intent.setType("image/*"); 
       intent.setAction(Intent.ACTION_GET_CONTENT); 
       startActivityForResult(Intent.createChooser(intent,"Complete action using"),PICK_FROM_FILE); 
      } 
     } 
    }); 
    final AlertDialog dialog = builder.create(); 
    mImageView = (ImageView) findViewById(R.id.imageView); 
    imagePicker = (ImageButton) findViewById(R.id.image_picker); 
    imagePicker.setOnClickListener(new View.OnClickListener(){ 
     @Override 
     public void onClick(View v){ 
      dialog.show(); 
     } 
    }); 

    @Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    if(requestCode != RESULT_OK) 
     return; 
    Bitmap bitmap = null; 
    String path =""; 
    if(requestCode == PICK_FROM_FILE) { 
     imageCaptureUri = data.getData(); 
     path = getRealPathFromURI(imageCaptureUri); 
     if(path == null) 
      path = imageCaptureUri.getPath(); 
     if(path != null){ 
      bitmap = BitmapFactory.decodeFile(path); 
     } 
    }else{ 
     path = imageCaptureUri.getPath(); 
     bitmap = BitmapFactory.decodeFile(path); 
    } 
    mImageView.setImageBitmap(bitmap); 
} 


    public String getRealPathFromURI(Uri contentURI){ 
    String[] proj = {MediaStore.Images.Media.DATA}; 
    Cursor cursor = managedQuery(contentURI,proj,null,null,null); 
    if(cursor == null) return null; 
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 
    cursor.moveToFirst(); 
    return cursor.getString(column_index); 
} 
+0

的可能的複製[對話挑選的圖像從畫廊或從相機(http://stackoverflow.com/questions/10165302/dialog-to-從相機中選擇圖像或從相機中取出) –

+0

只需使用此庫:https://github.com/jrvansuita/PickImage –

回答

0
  1. 首先,你需要使用許可WRITE_EXTERNAL_STORAGE在AndroidManifest.xml

  2. 在你的XML佈局:

    <ImageView 
        android:id="@+id/img" 
        android:layout_width="match_parent" 
        android:layout_height="380dp" 
        android:background="#f241c9" /> 
    
    <Button 
        android:id="@+id/btnCapture" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="center" 
        android:layout_marginTop="20dp" 
        android:text="Take Photo" /> 
    
    <Button 
        android:id="@+id/btnPick" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="center" 
        android:layout_marginTop="20dp" 
        android:text="Pick Photo" /> 
    

  3. 在您的活動類:

    private static final String TAG = "my_log"; 
    private static final int REQUEST_CAPTURE_FROM_CAMERA = 1; 
    private static final int REQUEST_PICK_FROM_FILE = 2; 
    private static final int REQUEST_CROP_INTENT = 3; 
    
    ImageView img; 
    Button btnCapture, btnPick; 
    File file; 
    
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
    
        img = (ImageView) findViewById(R.id.img); 
        btnCapture = (Button) findViewById(R.id.btnCapture); 
        btnPick = (Button) findViewById(R.id.btnPick); 
    
        btnCapture.setOnClickListener(new View.OnClickListener() { 
         @Override 
         public void onClick(View v) { 
          Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); 
          file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_captured.jpg"); 
          // put Uri as extra in intent object 
          intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); 
          startActivityForResult(intent, REQUEST_CAPTURE_FROM_CAMERA); 
         } 
        }); 
    
        btnPick.setOnClickListener(new View.OnClickListener() { 
         @Override 
         public void onClick(View v) { 
          Intent intent = new Intent(); 
          intent.setType("image/*"); 
          intent.setAction(Intent.ACTION_GET_CONTENT); 
          startActivityForResult(Intent.createChooser(intent, "Complete action using"), REQUEST_PICK_FROM_FILE); 
         } 
        }); 
    
    } 
    
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    
        if (resultCode != RESULT_OK) return; 
    
        if (requestCode == REQUEST_CAPTURE_FROM_CAMERA) { 
         try { 
          cropImage(Uri.fromFile(file)); 
         } catch (ActivityNotFoundException e) { 
          Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show(); 
          e.printStackTrace(); 
         } 
        } else if (requestCode == REQUEST_PICK_FROM_FILE) { 
         try { 
          cropImage(data.getData()); 
         } catch (ActivityNotFoundException e) { 
          Toast.makeText(this, "Your device does not support the crop action!", Toast.LENGTH_SHORT).show(); 
          e.printStackTrace(); 
         } 
        } else if (requestCode == REQUEST_CROP_INTENT) { 
         // Create an instance of bundle and get the returned data 
         Bundle extras = data.getExtras(); 
         // get the cropped bitmap from extras 
         Bitmap bitmap = extras.getParcelable("data"); 
         img.setImageBitmap(bitmap); 
         if (saveBitmapToStorage(bitmap)) { 
          Log.d(TAG, "Bitmap saved to file successful."); 
         } else { 
          Log.d(TAG, "Failed to save Bitmap to storage."); 
         } 
        } 
    
    } 
    
    public void cropImage(Uri picUri) { 
        //call the standard crop action intent 
        Intent cropIntent = new Intent("com.android.camera.action.CROP"); 
        //indicate image type and Uri of image 
        cropIntent.setDataAndType(picUri, "image/*"); 
        //set crop properties 
        cropIntent.putExtra("crop", "true"); 
        //indicate aspect of desired crop 
        cropIntent.putExtra("aspectX", 1); 
        cropIntent.putExtra("aspectY", 1); 
        //indicate output X and Y 
        cropIntent.putExtra("outputX", 256); 
        cropIntent.putExtra("outputY", 256); 
        //retrieve data on return 
        cropIntent.putExtra("return-data", true); 
        //start the activity - we handle returning in onActivityResult 
        startActivityForResult(cropIntent, REQUEST_CROP_INTENT); 
    } 
    
    private boolean saveBitmapToStorage(Bitmap finalBitmap) { 
        boolean result = false; 
    
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img_cropped.jpg"); 
        Log.d(TAG, "file path = " + file.getAbsolutePath()); 
    
        try { 
         FileOutputStream out = new FileOutputStream(file); 
         finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); 
         out.flush(); 
         out.close(); 
    
         // send Broadcast to notify this photo and see it in Gallery 
         Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
         Uri contentUri = Uri.fromFile(file); 
         mediaScanIntent.setData(contentUri); 
         sendBroadcast(mediaScanIntent); 
    
         result = true; 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
    
        return result; 
    } 
    
相關問題