我编写了一个方法,该方法在我的应用程序缓存目录中创建一个目录,然后提示用户拍照或从图库中选择照片。
如果用户拍摄新照片,该照片将以 profile.jpg 的形式保存到缓存中
我正在尝试获取从图库返回照片的 Intent ,以将返回的照片作为 profile.jpg 保存在我的应用程序的缓存目录中。
我很难实现这一点。
public void selectImage(View v) {
File newDir = new File(getExternalCacheDir(), "RecruitSwift");
if(!newDir.isDirectory())
newDir.mkdirs();
else
Toast.makeText(this, "Dir already exist", Toast.LENGTH_LONG).show();
if(newDir.canWrite())
imageFile = new File(newDir, "profile.jpg");
else
Toast.makeText(this, "Dir not writable", Toast.LENGTH_LONG).show();
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfileInterviewScreenActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")){
Intent takeProfileImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takeProfileImage.resolveActivity(getPackageManager()) != null) {
Uri imageUri = Uri.fromFile(imageFile);
takeProfileImage.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takeProfileImage, 1);
}
}
else if (options[item].equals("Choose from Gallery")){
Intent takeProfileImage = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Uri selectedImage = takeProfileImage.getData();
imageFile = selectedImage;
startActivityForResult(takeProfileImage, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
最佳答案
如果你想拍照或者挑选图片,你需要调用startActivityForResult
,然后重写onActivityResult
。下面是一些拍照的代码,大家看一下:
startActivityForResult
:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(AVATAR_FILE_TMP));
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, CODE_TAKE_PHOTO);
然后覆盖onActivityResult
:
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CODE_TAKE_PHOTO) {
cropImage(Uri.fromFile(AVATAR_FILE_TMP));
}
}
关于java - 将从图库中选择的照片保存到缓存目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29633598/