我尝试从相机获取图像并将其设置为“图像视图”并保存到图库中,图片已成功捕获,但是该图片未显示到“图像视图”中且未保存到图库中。我不知道问题出在哪里。
我在这里尝试过很多帖子,但仍然不能解决我的问题。
这是我的代码
定义:
android.support.v7.widget.Toolbar toolbar;
private String id_sales, pilihanUploadPp, imagePath;
private EditText namaEdt, usernameEdt, notelpEdt, emailEdt;
private ProgressDialog progress;
private CompositeDisposable disposables = new CompositeDisposable();
private SessionManager sessionManager;
private int CAMERA_PERM_CODE = 1;
private static final int IMG_REQUEST1 = 100, IMG_REQUEST2 = 200;
private ImageView pp_img;
onCreate方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ubah_profil);
sessionManager = new SessionManager(this);
namaEdt = findViewById(R.id.nama_edit_edt);
usernameEdt = findViewById(R.id.username_edit_edt);
notelpEdt = findViewById(R.id.telp_edit_edt);
emailEdt = findViewById(R.id.email_edit_edt);
pp_img = findViewById( R.id.pp_edit_iv );
Button ubahBtn = findViewById(R.id.ubah_edit_btn);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull( getSupportActionBar() ).setTitle("Ubah Profil");
ActionBar actionbar = getSupportActionBar();
assert actionbar != null;
actionbar.setDisplayHomeAsUpEnabled(true);
getIntentDataFromFragmentProfil();
ubahBtn.setOnClickListener(this);
pp_img.setOnClickListener( this );
}
onClick方法:
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.ubah_edit_btn:
updateProfil();
break;
case R.id.pp_edit_iv:
selectImage();
break;
}
}
selectImage方法:
private void selectImage() {
final CharSequence[] items = {"Kamera", "Galeri", "Batal"};
AlertDialog.Builder builder = new AlertDialog.Builder( UbahProfilActivity.this );
builder.setTitle( "Ubah Foto Profil" );
builder.setItems( items , (dialog , which) -> {
if (items[which].equals( "Kamera" )){
pilihanUploadPp = "Kamera";
if (ContextCompat.checkSelfPermission( UbahProfilActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
cameraIntent();
} else {
reqCameraPerms();
}
}
} );
builder.show();
}
cameraIntent方法:
private void cameraIntent(){
Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
if (intent.resolveActivity( getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
} catch (IOException ioex){
Toast.makeText( this , "Error: "+ioex , Toast.LENGTH_SHORT ).show();
}
if (photoFile!=null){
Uri outputFileUri = FileProvider.getUriForFile( this , "com.example.bismillah.newsahabatauto2000.Activity.provider" , photoFile );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult( intent, IMG_REQUEST1 );
}
}
}
createImageFile方法:
private File createImageFile() throws IOException {
String timeStamp =
new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir =
getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
imagePath = image.getAbsolutePath();
return image;
}
最后是onActivityResult方法:
@Override
protected void onActivityResult(int requestCode , int resultCode , Intent data) {
super.onActivityResult( requestCode , resultCode , data );
try{
if (requestCode==IMG_REQUEST1 && resultCode==RESULT_OK){
if (data !=null && data.getExtras() !=null){
Bitmap imageBitmap = (Bitmap) data.getExtras().get( "data" );
pp_img.setImageBitmap( imageBitmap );
}
}
}catch (Exception e){
Toast.makeText( this , "Error: "+e , Toast.LENGTH_SHORT ).show();
}
}
答案 0 :(得分:0)
尝试使用此代码对我完全有用,
private final static int CAMERA = 0,GALLERY = 1;
private static final int REQUEST_PERMISSIONS_EXTERNAL_STORAGE = 1;
private Uri selectedImage = null
private void onClickUploadPicture(){ requestAppPermissions(new String [] {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA}, REQUEST_PERMISSIONS_EXTERNAL_STORAGE,新的setPermissionListener(){ @Override 公共无效onPermissionGranted(int requestCode){ 新的ImagePicker(CreateBusinessAccountActivity.this,新的ImagePicker.onItemClick(){ @Override 公共无效onCameraClicked(){ displayCamera(); }
@Override
public void onGalleryClicked() {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, GALLERY);
}
}).show();
}
@Override
public void onPermissionDenied(int requestCode) {
showSnackBar(toolbar, getString(R.string.please_grant_permission), Snackbar.LENGTH_INDEFINITE,
getString(R.string.settings), () -> {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(intent);
});
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CAMERA:
if (resultCode == RESULT_OK) {
Log.e(TAG, String.valueOf(selectedImage));
glideUtils.loadCircleImageFromLocal("file://" + selectedImage, mBinding.companyLogo.ivUserImage);
userData.setProfileOrLogoUri(selectedImage);
mBinding.companyLogo.ivFlag.setVisibility(View.VISIBLE);
mBinding.companyLogo.ivFlag.setImageResource(R.drawable.ic_selected_check_with_green_circle);
mBinding.companyLogo.tvFullName.setText(getResources().getString(R.string.update_profile_pic));
}
break;
case GALLERY:
if (resultCode == RESULT_OK) {
assert data != null;
selectedImage = data.getData();
assert selectedImage != null;
Log.e(TAG, selectedImage.toString());
glideUtils.loadCircleImageFromLocal(new File(getRealPathFromURI(CreateBusinessAccountActivity.this, selectedImage)).getAbsolutePath(), mBinding.companyLogo.ivUserImage);
userData.setProfileOrLogoUri(Uri.parse(getRealPathFromURI(CreateBusinessAccountActivity.this, selectedImage)));
mBinding.companyLogo.ivFlag.setVisibility(View.VISIBLE);
mBinding.companyLogo.ivFlag.setImageResource(R.drawable.ic_selected_check_with_green_circle);
mBinding.companyLogo.tvFullName.setText(getResources().getString(R.string.update_profile_pic));
}
break;
}
答案 1 :(得分:0)
我使用Image Cropper进行拍摄,或者从手机中添加图片,然后对其进行裁剪, 并为我保存了这项功能:
File file = null;
String taskFolderPath = Environment.getExternalStorageDirectory().toString() + "/DCIM/myPhotos/" + sID[0] + sID[1];
String sType = "";
if (type == 1) {
String time = String.valueOf(cal.get(Calendar.MINUTE)) + String.valueOf(cal.get(Calendar.SECOND));
sType = "start-" + sID[0] + sID[1] + time; //sID is a String table
file = new File(taskFolderPath, sType + ".jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,50,stream); //0 - min, 100 - max quality, true if success
stream.flush();
stream.close();
} catch (IOException e) {
e.printStackTrace();
}