我使用以下代码将图像文件保存在指定的文件夹中: -
private void captureImage(int usertype, String id) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mFileURI = getOutputMediaFileUri(usertype, id);
if(mFileURI!=null)
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileURI);
else{
new AlertDialog.Builder(WorkspaceActivity.this)
.setTitle("Cannot create folder")
.setMessage("Unable to create directory please try later.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
if(mFileURI!=null){
// start the image capture Intent
if (usertype == PIC_OF_TEAM) {
startActivityForResult(intent,
CAMERA_CAPTURE_TEAM_IMAGE_REQUEST_CODE);
} else if (usertype == PIC_OF_STUDENT) {
startActivityForResult(intent,
CAMERA_CAPTURE_STUDENT_IMAGE_REQUEST_CODE);
}
}
}
/*
* returning image file
*/
private File getOutputMediaFile(int usertype, String id,
String packagename) {
String tempId = id;
File mediaStorageDir = null;
String userType = "";
// External sdcard location
if (usertype == PIC_OF_STUDENT) {
String studentLocalPicUrl = AppConstants.STUDENT_PIC_LOCAL_URL;
studentLocalPicUrl = studentLocalPicUrl.replace("/bibox/", "/bibox/"+mMentorID+"/");
File file = new File(studentLocalPicUrl);
mediaStorageDir = new File(Environment.getExternalStorageDirectory(),studentLocalPicUrl);
userType = AppConstants.PIC_STUDENT;
} else if (usertype == PIC_OF_TEAM) {
String teamLocalPicUrl = AppConstants.TEAM_PIC_LOCAL_URL;
teamLocalPicUrl = teamLocalPicUrl.replace("/bibox/", "/bibox/"+mMentorID+"/");
mediaStorageDir = new File(
Environment.getExternalStorageDirectory(),
teamLocalPicUrl);
userType = AppConstants.PIC_TEAM;
}
if (mediaStorageDir != null)
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MediaHelper", "failed to create directory");
return null;
}
}
// Create a media file name
File mediaFile = null;
String imagePath = mediaStorageDir.getPath() + File.separator + tempId+ ".jpg";
mediaFile = new File(imagePath);
if(mediaFile.exists()){
//If file already exists do this.
do{
imagePath = imagePath.replace(tempId, tempId+"_"+generateRandomNo());
mediaFile = new File(imagePath);
}while(mediaFile.exists());
}
//Assign the id, image path, user type
//So that we can use it for further use in the database.
mId = id;
mMediaPath = imagePath;
mUserType = userType;
return mediaFile;
}
public Uri getOutputMediaFileUri(int usertype, String id) {
File outputMediaFile = getOutputMediaFile(usertype, id, getPackageName());
if(outputMediaFile==null)
return null;
return Uri.fromFile(outputMediaFile);
}
常量的值是: -
public static String STUDENT_PIC_LOCAL_URL = "/bibox/img/student";
问题是在拍摄图像后,如果我删除了文件夹mMentorId,那么就会创建一个0bytes的垃圾文件,该文件的屏幕截图如下所示,我试过很多关于此的搜索,但没有是富有成效的。