android - 从图库中删除图像 - android
问题描述
我正在制作一个从相机捕获图像并将其上传到 Firebase 的应用程序。将图像上传到 firebase 后,我想从图库的 Camera 文件夹和另一个名为 Pictures 的文件夹中删除图像,该文件夹是在捕获图像后自动创建的。我尝试了 SO 的多种解决方案,但都没有奏效。我尝试使用 file.delete() 和路径从 uri 中删除图像,但图像仍然存在于上述文件夹中。我正在使用 API 21,并且我在某处阅读过我们无法通过 file.delete() 访问 sd 卡文件的内容,那么有什么解决方案?请提出适用于每台设备 >= API 19 的方法。另外,请提出一种无论图像保存在何处都有效的方法,即无论是外部存储器还是内部存储器,因为我不知道
我在这里提供了一些代码片段,如果需要其他任何内容,请告诉我。
我正在创建这样的意图对象:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
我在这里做上传工作:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data!= null){
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.waitwhilepicisuploaded);
mediaPlayer.start();
final Bitmap photo = (Bitmap) data.getExtras().get("data");
//the tap to open camera button disappears
tapCameraBtn.setVisibility(Button.GONE);
//setting the color of progress bar to white
progressBar.getIndeterminateDrawable().setColorFilter(ContextCompat.getColor(this, android.R.color.white), PorterDuff.Mode.SRC_IN );
//and now we make the progress bar visible instead of the button
progressBar.setVisibility(ProgressBar.VISIBLE);
mCount = FirebaseDatabase.getInstance().getReference().child(FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber().toString()).child("count");
uploadPhoto(mCount, photo);
}
}
public void uploadPhoto(DatabaseReference mCount, Bitmap photo){
final Uri uri = getImageUri(getApplicationContext(), photo);
final String userPhoneNumber = FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber();
uniquefilename = userPhoneNumber.toString();
mCount.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
photoCounter = dataSnapshot.getValue(Integer.class);
//uploading image captured to firebase
uploadPhotoToFirebase(uri, userPhoneNumber, uniquefilename, photoCounter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d("The read failed: ", "FAILED");
}
});
}
public void uploadPhotoToFirebase(Uri uri, final String userPhoneNumber, String uniquefilename, int photoCounter){
final StorageReference filepath = storageReference.child("/" + uniquefilename + "/photos/" + "photo_" + photoCounter);
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mediaPlayer.stop();
mediaPlayer.release();
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_SHORT).show();
deleteFile(uri);
uploadPhotoToKairos(uri,userPhoneNumber);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
Toast.makeText(getApplicationContext(), "URI not found", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(AddContactActivity.this, "Uploading finished!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(AddContactActivity.this, RecordAudioActivity.class);
startActivity(intent);
finish();
}
});
}
deleteFile(Uri uri){
File fdelete = new File(uri.getPath());
if (fdelete.exists()) {
if (fdelete.delete()) {
Log.d("file deleted" , uri.getPath());
} else {
Log.d("file not Deleted " , uri.getPath());
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
此外,清单文件中还有以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
我已经从 SO 的各种答案中删除了我尝试过的所有不需要的代码,这是原始代码。
解决方案
只需在任何目录中创建您自己的用于捕获的文件并将该 file_path(String) 保存在任何地方。
然后像这样将该文件传递给意图
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
//for nougat and above using file provider..
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, "provider path(like package)", file));
} else {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
}
startActivityForResult(takePictureIntent,
CAMERA_IMAGE_REQUEST);
从 file_path 获取 URI 或文件,并从文件路径获取所需的图像或位图。按文件路径删除文件。
请检查此文件提供程序
https://developer.android.com/reference/android/support/v4/content/FileProvider
推荐阅读
- javascript - 获取具有非空数组作为值的属性的对象键
- mongodb - mongo facet group 3 输出结果
- html - 用于下划线的 Material UI CSS 动画
- actionscript-3 - 使用动作脚本 3 检测颜色
- python - ![远程拒绝] master -> master (pre-receive hook denied) 错误:未能将一些参考推送到“https://git.heroku.com/stark-dawn-54447.git”
- haskell - Haskell 检查嵌套数据
- android - 在Pagedlist Android中加载更多页面时需要回调
- python - 使用 pyomo 并行解决许多实例
- amazon-web-services - 通过站点到站点 VPN 从本地连接到 AWS s3
- python - 如何从 python 脚本中的单个 bibtex 输入字段获取可读的 unicode 字符串