Android studio 拍照后图片在imageview显示出来
时间: 2024-05-12 07:16:46 浏览: 81
可以使用以下代码在Android中拍照并将图像显示在ImageView上:
```java
// 在AndroidManifest.xml中添加Camera权限
<uses-permission android:name="android.permission.CAMERA" />
// MainActivity.java文件中的代码
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
static final int REQUEST_IMAGE_CAPTURE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
//监听按钮点击事件
Button takePhotoButton = findViewById(R.id.button);
takePhotoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
// 适用于拍照的Intent
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
// 拍照后显示图片在ImageView上
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
}
```
这段代码将启动相机应用程序,并等待您拍照。在用户拍照后,使用 `onActivityResult()` 将图像显示在 ImageView 中。
阅读全文