Android-图像未显示在ImageView中,也未从相机保存到图库



我尝试从相机中获取图像,并将其设置为"图像视图"并保存到图库,图片已成功捕获,但图片未显示到"图像视图》,也未保存到图库。我不知道问题出在哪里。

我在这里发了很多帖子,但仍然没有解决我的问题。

这是我的代码

定义:

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;

on创建方法:

@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;
}

最后是ActivityResult方法:

@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();
}
}

试试这个代码,它对我来说非常有效,

私有最终静态int CAMERA=0,GALLERY=1;

private static final int REQUEST_PERMISSIONS_EXTERNAL_STORAGE = 1;
private Uri selectedImage = null

单击上传图片((时出现私有无效{requestAppPermissions(new String[]{Manifest.permission.WRITE_EEXTERNAL_STORAGE,Manifest.license.CAMERA},REQUEST_PERMISSIONS_EXTERNAL_STORAGE,新的setPermissionListener(({@Overridepublic void onPermissionGranted(int requestCode({new ImagePicker(CreateBusinessAccountActivity.this,new ImagePicker.onItemClick(({@OverrideCameraClicked((上的公共无效{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;

}

我使用图像裁剪器进行捕捉,或者添加手机中的图像,并对其进行裁剪,保存这对我来说很有效:

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();
}

最新更新