android调用系统相机进行拍照,并显示在主界面上,超级简单

主活动的布局文件:activity_main.xml

定义一个按钮用于启动系统相机、定义一个ImageView用于展示刚刚拍摄的图片

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击拍摄" />

<ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

在主活动MainActivity.java文件中拿到按钮和ImageView,并且为按钮添加事件监听

button = findViewById(R.id.button1);
        imageView = findViewById(R.id.image);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent,TAKE_PHOTO);
            }
        });

重写主活动的 onActivityResult 方法用于拿到拍摄结束后的数据。

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == TAKE_PHOTO){//可以判断是我们那个Intent发出的请求
                Bundle bundle = data.getExtras();//在相机这个应用中包含的是整个二进制流
                Bitmap bitmap = (Bitmap) bundle.get("data");
                imageView.setImageBitmap(bitmap);
            }
        }
    }

运行效果如果所示,注意,返回的Intent中所包含的只是一个缩略图,可以发现会比较模糊。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章