在我的应用程序中,我必须从本机相机应用程序捕获照片,然后将其存储在我想要的文件夹中,然后在新的 Activity 中显示捕获的图像。到目前为止我的代码
启动本机相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
我的其他方法
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/**Create a file for saving an image*/
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "KidzPuzzle");
//Create a storage directory if it does not exist
if(! mediaStorageDir.exists()){
if(! mediaStorageDir.mkdirs()){
Log.d("KidzPuzzle", "Failed to create directory");
return null;
}
}
//Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = null;
if(type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg" );
return mediaFile;
}else{
return null;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE){
if(resultCode == RESULT_OK){
//Image created and saved successfully to the specified fileUri
//Toast.makeText(this, "Image saved to : \n"+data.getDataString(), Toast.LENGTH_LONG).show();
String filePath = ((Uri) data.getExtras().get(MediaStore.EXTRA_OUTPUT)).toString();
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
startActivity(new Intent(this, SplitImageActivity.class).putExtra("image", bitmap));
}else if(resultCode == RESULT_CANCELED){
//user canceled the captured image
}else{
//Image capture failed
}
}
}
onActivityResult 中的意图变量数据始终为空。请帮助我哪里出错了。
注意:当我调试它时,控件总是满足 RESULT_OK 条件并显示NullPointerException,因为data的值。
还有一件事,如果我不使用
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
此代码在启动本机相机之前,则数据不为空。
请帮我。