Android: 将相册中可见的照片文件写入 SD 卡

Android: write photo files on SD Card that are viewable in the gallery

我正在尝试找到一种方法(与 android kitkat 和 next 兼容)将照片写入 SD 卡并使它们对图库应用程序可见。

我试过直接在 /storage/externalSdCard/DCIM/ 上写,但我当然不能,因为我是 运行 kitkat。

void saveImage() {
        File filename;
        try {
            String path = Environment.getExternalStorageDirectory().toString();

            new File(path + "/folder/subfolder").mkdirs();
            filename = new File(path + "/folder/subfolder/image.jpg");

            FileOutputStream out = new FileOutputStream(filename);

            bitMapImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();

            MediaStore.Images.Media.insertImage(getContentResolver(), filename.getAbsolutePath(), filename.getName(), filename.getName());

            Toast.makeText(getApplicationContext(), "File is Saved in  " + filename, 1000).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Ok, I can write inside and the photo is on the SDCard. But I can't see it in the Galery app

首先,当您完成写入文件后,调用 flush(),然后调用 getFD().sync(),然后调用 close(),全部在您的 FileOutputStream.

然后,使用MediaScannerConnection及其scanFile()方法得到由MediaStore.

索引的新写入文件