下载图像并将其存储在 android 中的图库应用程序中

Download Image and store it in Gallery app in android

我想将图像文件保存在图库中,以便可以从图库应用程序中查看图像。

但我想要创建一个单独的目录,就像我们在图库应用程序中为 whatsapp 图片等应用程序创建的那样。

到目前为止,我已经编写了这段代码来下载图片

public void createDir(){
  File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), DIR_NAME);
    Log.d(LOG_TAG, "dir pictr :" + dir.toString());
    if (!dir.exists()) {
        dir.mkdir();
        Log.d(LOG_TAG, "dir not exists and created first time");
    } else {
        Log.d(LOG_TAG, "dir exists");
    }
}

以上代码在图库目录中创建了目录

Uri imageLink = Uri.parse(downloadUrlOfImage);  // this is download link like www.com/abc.jpg

CreateDir();
DownloadManager.Request request = new DownloadManager.Request(imageLink);

File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), DIR_NAME);
String absPath = dir.getAbsoultePath();
request.setDestinationUri(Uri.parse(absPath + "image.jpg"));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

DownloadManager dm = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);

但这给了我错误,因为 java.lang.IllegalArgumentException: Not a file URI: /storage/sdcard0/Pictures/FreeWee/1458148582.jpg

基本上我想要的是保存图像,并且该图像必须显示在我命名的某个目录下的图库应用程序中。

如果不明白请提问,以便我改进我的问题。 我该如何继续?

正如@RoyFalk 所指出的,您的代码中有 2 个问题。

所以你可以使用这个代码片段

String filename = "filename.jpg";
String downloadUrlOfImage = "YOUR_LINK_THAT_POINTS_IMG_ON_WEBSITE";
    File direct =
            new File(Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .getAbsolutePath() + "/" + DIR_NAME + "/");


    if (!direct.exists()) {
        direct.mkdir();
        Log.d(LOG_TAG, "dir created for first time");
    }

    DownloadManager dm = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
    Uri downloadUri = Uri.parse(downloadUrlOfImage);
    DownloadManager.Request request = new DownloadManager.Request(downloadUri);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false)
            .setTitle(filename)
            .setMimeType("image/jpeg")
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_PICTURES,
                    File.separator + DIR_NAME + File.separator + filename);

    dm.enqueue(request);

您将在 DIR_NAME 下的图库应用程序中看到图片。 希望对您有所帮助。