android:删除图像

时间:2012-05-23 08:56:25

标签: android image gallery

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

new  File(filename).delete ();

这实际上是删除了该文件。但是图片仍然可以在画廊中看到。

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

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

但在这里我得到了例外:

  

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

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

10 个答案:

答案 0 :(得分:34)

我看到很多答案暗示使用

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

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

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

答案 1 :(得分:28)

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

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

删除图片后使用

刷新图库使用以下代码发送广播

(适用于< KITKAT API 14)

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

对于> = 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);
              }
            });

因为:

ACTION_MEDIA_MOUNTED

在KITKAT(API 14)中已弃用。


已于2015年9月9日编辑

下面代码

的工作正常检查
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())));
        }
    }

下面是日志

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

答案 2 :(得分:23)

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

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

此代码适用于我,我认为最好使用Intent.ACTION_MEDIA_MOUNTED

重新安装整张SD卡

答案 3 :(得分:13)

要删除图片,

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

答案 4 :(得分:5)

我尝试了所有这些解决方案,但在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});
        }
    }
}

我还在Android 4.4和5.1中对此进行了测试,它运行良好。

答案 5 :(得分:4)

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

此代码有效,但资源非常昂贵。它卸下了&amp;然后安装SDCard可能会影响某些应用程序或占用大量系统资源以刷新库。我仍然在寻找一个最好的选择&amp;如果我得到,我会发布。

答案 6 :(得分:0)

在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")
            }
        } 
    }
}

答案 7 :(得分:0)

我遇到了同样的问题,并且尝试了三种不同的方法来删除图像。有时它正在工作,有时却没有。现在花了太多时间后,我拥有的每种方法都会删除图像。我要说的是:请谨慎处理位图。我正在拍照,坚持下去,然后根据需要旋转:

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

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

也许这只是我的问题,但是一旦我删除了它,对我很有帮助,所以我想特别注意一下您如何处理图像。就我而言,我使用了前面提到的答案:

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

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

希望有帮助!

答案 8 :(得分:0)

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

答案 9 :(得分:0)

DocumentFile.fromSingleUri(context, uri).delete();

对我来说很棒