将图像保存在图库中并获取文件路径 android

save image in gallary and get file path android

我是 Android 的新手。我想在 URL 的图库中保存一个 image 并获取保存图像的文件名和路径。所以我可以在图库中用 onclick 打开它。 我尝试了很多解决方案,但找不到正确的方法来保存 file path

我只想在 onclick 上以画廊形式 URL 打开一张图片。

我的代码

   activity_edit_profile_basic_imageview_profile_icon.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                galleryAddPic();

            }
        });

    private void galleryAddPic() {
     String fileName = intentProfilePic.substring(intentProfilePic.lastIndexOf('/') + 1);
     Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
     File f = new File(intentProfilePic);
     Uri contentUri = Uri.fromFile(f);
     mediaScanIntent.setData(contentUri);
     this.sendBroadcast(mediaScanIntent);
     showImage(fileName);
   }

   public void showImage(String fileName) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file://" +"/sdcard/"+fileName ), "image/*");
    startActivity(intent);
   }

连我自己都不知道自己做的对还是错。

当我点击 imageview 时,我的应用程序崩溃并显示错误...

 android.os.FileUriExposedException: file:///sdcard/4f5eac461a2a75431d392dd71ffebf97.jpg exposed beyond app through Intent.getData()

我知道我走错了路。所以我想知道如何获取文件路径并保存图像。然后使用文件路径再次使用 onclink 打开它。我也不知道存不存文件

使用这个:

启动异步任务:

DownloadSelctedIMG d = new DownloadSelctedIMG();
        d.execute();

现在 AsynchTask Class:

class DownloadSelctedIMG extends AsyncTask<String, String, Void> {

        String ImgPath = "";       

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = new ProgressDialog(ReferActivity.this);
            loading.setMessage("Please Wait..");
            loading.setCancelable(false);
            loading.show();
        }

        protected Void doInBackground(String... arg0) {
            File f = new File("IMAGE_URL");
            String filename = "image_name.jpg";
            File wallpaperDirectory = new File(Environment.getExternalStorageDirectory().toString() + "/FOLDER/"
            );                            

            wallpaperDirectory.mkdirs();
            ImgPath = wallpaperDirectory.getPath()+ filename;

            String myu_recivedimage = "IMAGE_URL";
            int count;
            try {
                URL myurl = new URL(myu_recivedimage);
                URLConnection conection = myurl.openConnection();

                int lenghtOfFile = conection.getContentLength();
                conection.connect();
                int filelength = conection.getContentLength();
                InputStream inpit = new BufferedInputStream(myurl.openStream());
                OutputStream output = new FileOutputStream(ImgPath);

                byte data[] = new byte[1024];
                long total = 0;
                while ((count = inpit.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                }
                output.flush();
                output.close();
                inpit.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            if (loading != null && loading.isShowing()) {
                loading.dismiss();
            }
            try {


                /*--- SAVED IMAGE PATH--ImgPath   ---------*/

                    File file = new File(ImgPath);





            } catch (Exception e) {
            }
        }
    }

在图库中打开图片:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri photoURI = FileProvider.getUriForFile(getApplicationContext(),
                                        BuildConfig.APPLICATION_ID + ".provider",
                                        new File(ImgPath));


            intent.setDataAndType(photoURI, "image/*");
            startActivity(intent);

如果您的 targetSdkVersion 是 24 或更高版本,我们必须使用 FileProvider class 来授予对特定文件或文件夹的访问权限,以便其他应用可以访问它们。

将 file:// uri 替换为 content:// uri 的步骤:

将此添加到您的清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths"/>
</provider>
</application>
</manifest>

然后在res文件夹下的xml文件夹中创建一个provider_paths.xml文件。如果文件夹不存在,可能需要创建。该文件的内容如下所示。它描述了我们想共享对根文件夹 (path=".") 中名为 external_files.

的外部存储的访问
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>

最后一步是更改下面的代码行

Uri photoURI = Uri.fromFile(createImageFile());

Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", createImageFile());