以下是MainActivity.java的代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePictureButton = findViewById(R.id.button_image);
imageView = findViewById(R.id.imageView);
这是拍照的ocClick()函数。这会调用相机并捕获图像。
public void takePicture(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName = getPictureName();
File imageFile = new File(pictureDirectory, pictureName);
Uri pictureUri = Uri.fromFile(imageFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, pictureUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
private String getPictureName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
return "IMG_" + timestamp + ".jpg";
}
这是用于打开Gallery的onClick()函数。可以访问画廊,但是我保存照片的目录未显示
public void openGallery (View view)
{
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
photoPickerIntent.setDataAndType(data, "image/*");
startActivityForResult(photoPickerIntent, IMAGE_GALLERY_REQUEST_CODE);
}
这是onActivityResult()方法。
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (requestCode == RESULT_OK) {
}
}
if (requestCode == IMAGE_GALLERY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Uri imageUri = data.getData();
// declare a stream to read data from sdCard
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(imageUri);
Bitmap image = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "unable to open image", Toast.LENGTH_LONG).show();
}
}
}
}
谁能告诉我我哪里出错了。我没有为此解决方案。谁能帮我。预先感谢。