2013-12-21 80 views
1

我正在嘗試從MainActivity的默認相機意圖中拍攝一張照片,然後將該圖像放入同一活動的ImageView中。嘗試顯示從相機意圖拍攝的圖像

我保存圖像,使得拍攝的圖像將覆蓋以前拍攝的圖像(在這種情況下,我所說的圖像test.jpg,我將它存儲在SD卡)

我現在有我的代碼的問題是ImageView顯示上次應用程序運行時拍攝的照片。

這是我的代碼。

public class MainActivity extends Activity 
{ 
ImageView imv; 
@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    imv = (ImageView)findViewById(R.id.imv); 
    Uri uri = null; 
    String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/test.jpg"; 
    try 
    { 
     uri = takePhoto(path); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    imv.setImageURI(uri); 
} 

private Uri takePhoto(String path) throws IOException 
{ 
    File photo = new File(path); 
    photo.createNewFile(); 
    Uri fileUri = Uri.fromFile(photo); 
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 
    startActivityForResult(cameraIntent, 0); 
    fileUri = Uri.fromFile(new File(path)); 
    return fileUri; 
} 
} 
+0

http://chintankhetiya.wordpress.com/2013/12/14/picture-selection-from -camera-gallery/ –

+0

你的'onActivityResult'方法在哪裏? – GrIsHu

+0

看看我的答案。 – GrIsHu

回答

2

嘗試設置圖像onActivityResult如下:

protected void onActivityResult(int requestCode, int resultCode, Intent ata)          
      { 
if (requestCode == 0) { 
    if (resultCode == RESULT_OK) { 

     imv = (ImageView)findViewById(R.id.imv); 
     Bitmap photo = (Bitmap) data.getExtras().get("data"); 
     imv.setImageBitmap(photo); 
    }}} 
+0

謝謝。這使它工作。 onActivityResult是做什麼的?你能向我解釋這個嗎? –

+1

當用戶完成後續活動並將結果返回到當前活動時,系統將調用您的活動的'onActivityResult()'方法。由Android的Camera應用程序返回的結果'Intent'提供了一個內容'Uri'來標識捕獲的圖像。爲了成功處理結果,您必須瞭解'Intent'結果的格式。當返回結果的活動是您自己的活動之一時,這樣做很容易。 Android平臺附帶的應用程序提供了他們自己的API,您可以依賴特定的結果數據。 – GrIsHu

+1

'onActivityResult'當您啓動的活動退出時調用,爲您提供您啓動的'requestCode',返回的'resultCode'以及任何其他數據。如果活動明確地返回該結果,沒有返回任何結果或在其操作期間崩潰,則'resultCode'將是'RESULT_CANCELED'。 – GrIsHu

0
private static final int  PICK_CONTACT_REQUEST = 0 ; 
protected void onActivityResult(int requestCode, int resultCode, 
       Intent data) { 
      if (requestCode == PICK_CONTACT_REQUEST) { 
       if (resultCode == RESULT_OK) { 

        imv.setImageURI(uri); 

       } 
      } 
     } 

坐落在onactivity圖像導致它會顯示在相機拍攝的新形象。

0

試試這個,

private Uri takePhoto(String path) throws IOException 
    { 
     File photo = new File(path); 
     photo.createNewFile(); 
     if(photo.exists()) 
      photo.delete(); 
     photo = new File(path); 
     Uri fileUri = Uri.fromFile(photo); 
     Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); 
     startActivityForResult(cameraIntent, 0); 
     fileUri = Uri.fromFile(new File(path)); 
     return fileUri; 
    } 
相關問題