如何在Android上存储图像到SD卡后显示图像

时间:2018-05-26 19:32:03

标签: java android android-gallery

在我的应用程序中,我想从服务器下载图像并将其存储到 SD卡 我写下面的代码,我可以下载并存储在SD卡上 但是将图像存储到SD卡后没有显示到图库中!

我的代码:

private void createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
        File direct = new File(Environment.getExternalStorageDirectory() + "/MyApp/Wallpaper");

        if (!direct.exists()) {
            File wallpaperDirectory = new File("/sdcard/MyApp/Wallpaper/");
            wallpaperDirectory.mkdirs();
        }

        File file = new File(new File("/sdcard/MyApp/Wallpaper/"), fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            showReturnMessage("Message","Successfully saved :) ",R.color.alertSuccess);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

怎么可能?

1 个答案:

答案 0 :(得分:0)

每次保存图像时都需要刷新图库。保存后尝试调用此方法:

static public void notifyMediaScannerService(Context context, String path) {
    MediaScannerConnection.scanFile(context,
            new String[] { path }, null,
            new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri uri) {
            Log.i("ExternalStorage", "Scanned " + path + ":");
            Log.i("ExternalStorage", "-> uri=" + uri);
        }
    });
}
相关问题