android:删除图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10716642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:44:22  来源:igfitidea点击:

android : deleting an image

androidimagegallery

提问by png

I am deleting an image file from my application. I was doing

我正在从我的应用程序中删除一个图像文件。我在做

new  File(filename).delete ();

This was actually deleting the file. But the image was still visible in the gallery.

这实际上是删除文件。但图像在画廊中仍然可见。

On search i found that we should use

在搜索中我发现我们应该使用

getContentResolver().delete(Uri.fromFile(file), null,null);to delete

getContentResolver().delete(Uri.fromFile(file), null,null);删除

But here i am getting the exception:

但在这里我得到了例外:

Unknown file URL. java.lang.IllegalArgumentException: Unknown URL file:///mnt/sdcard/DCIM/Camera/IMG_20120523_122612.jpg

未知的文件 URL。java.lang.IllegalArgumentException: Unknown URL file:///mnt/sdcard/DCIM/Camera/IMG_20120523_122612.jpg

When i see with any file browser, this particular image is present. Please help me to fix this issue. Is there any other way to update gallery when image is physically deleted

当我使用任何文件浏览器查看时,会出现此特定图像。请帮我解决这个问题。物理删除图像时,是否还有其他方法可以更新图库

回答by Tanner Perrien

I've seen a lot of answers suggesting the use of

我已经看到很多建议使用的答案

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" +  Environment.getExternalStorageDirectory())));

This works but causes the Media Scanner to re-scan the media on the device. A more efficient approach would be to query/delete via the Media Store content provider:

这有效,但会导致媒体扫描仪重新扫描设备上的媒体。更有效的方法是通过媒体商店内容提供商查询/删除:

// Set up the projection (we only need the ID)
String[] projection = { MediaStore.Images.Media._ID };

// Match on the file path
String selection = MediaStore.Images.Media.DATA + " = ?";
String[] selectionArgs = new String[] { file.getAbsolutePath() };

// Query for the ID of the media matching the file path
Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
if (c.moveToFirst()) {
    // We found the ID. Deleting the item via the content provider will also remove the file
    long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
    Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
    contentResolver.delete(deleteUri, null, null);
} else {
    // File not found in media store DB
}
c.close();

回答by Dhaval Parmar

Use the code below, it may help you.

使用下面的代码,它可能对您有所帮助。

File fdelete = new File(file_dj_path);
if (fdelete.exists()) {
    if (fdelete.delete()) {
        System.out.println("file Deleted :" + file_dj_path);
    } else {
        System.out.println("file not Deleted :" + file_dj_path);
    }
}


to refresh gallery after deleting image use below code for send Broadcast

删除图像后刷新画廊使用下面的代码发送广播

(for < KITKAT API 14)

(对于 < 奇巧 API 14)

 sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
 Uri.parse("file://" +  Environment.getExternalStorageDirectory())));

For >= KITKAT API 14 use below code

对于 >= KITKAT API 14 使用以下代码

MediaScannerConnection.scanFile(this, new String[] { Environment.getExternalStorageDirectory().toString() }, null, new MediaScannerConnection.OnScanCompletedListener() {
            /*
             *   (non-Javadoc)
             * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
             */
            public void onScanCompleted(String path, Uri uri) 
              {
                  Log.i("ExternalStorage", "Scanned " + path + ":");
                  Log.i("ExternalStorage", "-> uri=" + uri);
              }
            });

Because:

因为:

ACTION_MEDIA_MOUNTED

is deprecated in KITKAT(API 14).

在 KITKAT(API 14) 中已弃用。



EDITED 04-09-2015

编辑 04-09-2015

its working fine check below code

它的工作正常检查下面的代码

public void deleteImage() {
        String file_dj_path = Environment.getExternalStorageDirectory() + "/ECP_Screenshots/abc.jpg";
        File fdelete = new File(file_dj_path);
        if (fdelete.exists()) {
            if (fdelete.delete()) {
                Log.e("-->", "file Deleted :" + file_dj_path);
                callBroadCast();
            } else {
                Log.e("-->", "file not Deleted :" + file_dj_path);
            }
        }
    }

    public void callBroadCast() {
        if (Build.VERSION.SDK_INT >= 14) {
            Log.e("-->", " >= 14");
            MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
                /*
                 *   (non-Javadoc)
                 * @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
                 */
                public void onScanCompleted(String path, Uri uri) {
                    Log.e("ExternalStorage", "Scanned " + path + ":");
                    Log.e("ExternalStorage", "-> uri=" + uri);
                }
            });
        } else {
            Log.e("-->", " < 14");
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                    Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        }
    }

below is logs

下面是日志

09-04 14:27:11.085    8290-8290/com.example.sampleforwear E/-->﹕ file Deleted :/storage/emulated/0/ECP_Screenshots/abc.jpg
09-04 14:27:11.085    8290-8290/com.example.sampleforwear E/-->﹕ >= 14
09-04 14:27:11.152    8290-8290/com.example.sampleforwear E/﹕ appName=com.example.sampleforwear, acAppName=/system/bin/surfaceflinger
09-04 14:27:11.152    8290-8290/com.example.sampleforwear E/﹕ 0
09-04 14:27:15.249    8290-8302/com.example.sampleforwear E/ExternalStorage﹕ Scanned /storage/emulated/0:
09-04 14:27:15.249    8290-8302/com.example.sampleforwear E/ExternalStorage﹕ -> uri=content://media/external/file/2416

回答by Cody

File file = new File(photoUri);
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoUri))));

This code works for me and I think it better than remount whole SD card with Intent.ACTION_MEDIA_MOUNTED

这段代码对我有用,我认为它比重新安装整个 SD 卡更好 Intent.ACTION_MEDIA_MOUNTED

回答by Darshan Dorai

To delete image,

要删除图像,

ContentResolver contentResolver = getContentResolver();
contentResolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            MediaStore.Images.ImageColumns.DATA + "=?" , new String[]{ imagePath });

回答by Marco Menardi

I tried all those solutions but had no luck in Android 6.
In the end, I found this snipped of code that worked fine.

我尝试了所有这些解决方案,但在 Android 6 中没有运气。
最后,我发现这段代码运行良好。

public static void deleteFileFromMediaStore(final ContentResolver contentResolver, final File file) {
    String canonicalPath;
    try {
        canonicalPath = file.getCanonicalPath();
    } catch (IOException e) {
        canonicalPath = file.getAbsolutePath();
    }
    final Uri uri = MediaStore.Files.getContentUri("external");
    final int result = contentResolver.delete(uri,
            MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
    if (result == 0) {
        final String absolutePath = file.getAbsolutePath();
        if (!absolutePath.equals(canonicalPath)) {
            contentResolver.delete(uri,
                    MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
        }
    }
}

I also tested this in Android 4.4 and 5.1 and it works perfectly.

我还在 Android 4.4 和 5.1 中对此进行了测试,效果很好。

回答by Rajiv

sendBroadcast(new Intent(
           Intent.ACTION_MEDIA_MOUNTED,
           Uri.parse("file://" +  Environment.getExternalStorageDirectory())));

This code works, but it is very resource expensive. It unmounts & then mounts the SDCard which may affect some applications or take huge system resources in order to refresh the gallery. I am still looking for a best alternative & will post if i get one.

此代码有效,但资源非常昂贵。它卸载然后挂载 SDCard,这可能会影响某些应用程序或占用大量系统资源以刷新图库。我仍在寻找最好的替代方案,如果我得到一个,我会发布。

回答by f.trajkovski

I had the same issue, and I tried three different methods to delete an image. Sometimes it was working sometimes it wasn't. After too much time spent now every method that I have will delete the image.What I wanna say is: BE CAREFUL WITH PROCESSING BITMAP. I was taking a picture persist it and then rotate if needed:

我遇到了同样的问题,我尝试了三种不同的方法来删除图像。有时它工作有时它不是。现在花费太多时间后,我拥有的每种方法都会删除图像。我想说的是:小心处理位图。我正在拍照,将其保留,然后根据需要旋转:

public static Bitmap rotatePictureToPortraitMode(String filePath, Bitmap myBitmap) {
try {
    ExifInterface exif = new ExifInterface(filePath);
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
    Log.d("EXIF", "Exif: " + orientation);
    Matrix matrix = new Matrix();
    if (orientation == 6) {
        matrix.postRotate(90);
    } else if (orientation == 3) {
        matrix.postRotate(180);
    } else if (orientation == 8) {
        matrix.postRotate(270);
    }
    myBitmap = Bitmap.createBitmap(myBitmap, 0, 0, myBitmap.getWidth(), myBitmap.getHeight(), matrix, true); // rotating bitmap
} catch (Exception e) {

}
return myBitmap;
}

after that I tried to delete the image but as I said previously it wasn't working. Removing this method helped to me to solve the issue.

之后,我尝试删除该图像,但正如我之前所说,它不起作用。删除此方法有助于我解决问题。

Maybe this was only my issue but as soon as I removed this it helped me a lot, so I wanna say careful how you are processing the image. For my case I used the answer that is previously mentioned :

也许这只是我的问题,但是一旦我删除了它,它对我有很大帮助,所以我想说的是你是如何处理图像的。对于我的情况,我使用了前面提到的答案:

File file = new File(photoUri);
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, 
Uri.fromFile(new File(photoUri)))); 

Hope it helps!

希望能帮助到你!

回答by Gopal Reddy

public static boolean deltefolderwithimages(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deltefolderwithimages(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    return dir.delete();
}

回答by Jéw?m'

In Kotlin you can do this :

在 Kotlin 中,您可以这样做:

private fun deleteImage(path: String) {
    val fDelete = File(path)
    if (fDelete.exists()) {
        if (fDelete.delete()) {
            MediaScannerConnection.scanFile(this, arrayOf(Environment.getExternalStorageDirectory().toString()), null) { path, uri ->
                Log.d("debug", "DONE")
            }
        } 
    }
}