簡體   English   中英

嘗試顯示從相機意圖拍攝的圖像

[英]Trying to display image taken from camera intent

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

我正在保存圖像,以使拍攝的圖像覆蓋先前拍攝的圖像(在這種情況下,我將圖像稱為test.jpg並將其存儲在sdcard中)

我的代碼現在遇到的問題是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;
}   
}

嘗試在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);
    }}}
 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);

                 }
             }
         }

將圖像設置為不活動狀態,它將顯示從相機拍攝的新圖像。

嘗試這個,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM