主活动的布局文件: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中所包含的只是一个缩略图,可以发现会比较模糊。



本文详细介绍了如何在Android应用中使用系统相机拍摄照片,并将拍摄的照片显示在ImageView上。通过定义按钮和ImageView的布局,设置按钮点击事件来启动相机,以及在onActivityResult方法中获取并显示拍摄的图片。
5809

被折叠的 条评论
为什么被折叠?



