如何在Android内部存储中创建用于图像的子目录

4
我正在编写一个应用程序,用于存储用户的个人资料信息和联系方式。用户资料和联系信息还包括图像/位图。我想将图像存储在内部存储中,并使用Picasso库显示图像。我希望应用程序创建一个个人资料目录来存储个人资料图像,同样地,也要为联系人创建一个目录。我想使用Picasso从文件中检索图像,并在ImvageView上显示它,如下所示。
Picasso.with(context)
       .placeholder(R.drawable.user_placeholder)
       .error(R.drawable.user_placeholder_error)
       .load("file:///somepath/profile.png")
       .into(imageView);

我不确定应用程序如何创建子目录并存储图片。提供给Picasso加载图像到ImageView的路径是什么?

编辑1

我认为可以使用getApplicationContext().getFilesDir().getAbsolutePath()来获取路径,但我还不确定如何为个人资料和联系人创建子目录?

1个回答

8
在 Android 中,有一个内部存储目录,您的应用可以在其中存储任何类型的文件;您可以使用 Context.getFilesDir() 来检索它。您还可以使用 File.mkdir() 创建子目录。我不知道 Picasso 是否会处理此操作,但为确保安全,可以事先创建该目录。确定路径的代码如下所示:
File makeAndGetProfileDirectory(String profileName) {
    // determine the profile directory
    File profileDirectory = new File(context.getFilesDir(), profileName);

    // creates the directory if not present yet
    profileDirectory.mkdir();

    return profileDirectory;
}

现在您可以使用此方法获取一个目录,用于存储配置文件数据,包括图片。假设每个配置文件都将有一个名为picture.jpg的文件; Picasso的代码如下:

String profileName = "foo"; // replace with the profile you want to show
File profileDir = makeAndGetProfileDirectory(profileName);
File profilePictureFile = new File(profileDir, "picture.jpg");

// now use Picasso to read it
Picasso.with(context)
       .placeholder(R.drawable.user_placeholder)
       .error(R.drawable.user_placeholder_error)
       .load(profilePictureFile)
       .into(imageView);

希望这有所帮助。

谢谢提供答案。但我仍然不清楚如何将图像存储在内部存储中。我将尝试以下代码片段:`File myImage = new File(storagePath, Long.toString(System.currentTimeMillis()) + ".jpg"); try { FileOutputStream out = new FileOutputStream(myImage); outputImage.compress(Bitmap.CompressFormat.JPEG, 80, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); }` - Kumari Sweta
图片从哪里来?您确实可以使用FileOutputStream写入文件,但是您需要从某个地方获取图像数据... - ris8_allo_zen0
我将从位图对象中获取图像数据。 - Kumari Sweta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接