![](/img/trans.png)
[英]android : how to add image from gallery and delete image with a Button
[英]delete image from gallery - 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.