java - 如何访问从网络下载的图像

标签 java android

我使用此代码从网络下载了图像,并将其直接保存到应用程序特定的内部存储中。

is = url.openConnection().getInputStream();
os = LoginActivity.this.openFileOutput(id + ".jpg", Context.MODE_PRIVATE);
int read;
byte[] data = new byte[1024];
while ((read = is.read(data)) != -1)
    os.write(data, 0, read);

如何使用 Drawable 访问此存储的图像?我尝试使用以下代码打开它,但操作导致文件未找到异常。

File imgPath = new File(id + ".jpg");
profilePic.setImageDrawable(Drawable.createFromPath(imgPath.getPath()));

最佳答案

假设您在以下代码行中调用 os.close()

实例化 File 对象时需要指定路径。执行以下操作:

File imgPath = new File(yourContext.getFilesDir(), id + ".jpg");

正如 getFilesDir() 方法的文档中所述:

Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.

关于java - 如何访问从网络下载的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20445567/

相关文章:

java - 一对一映射问题

android - AlarmManager 设置为 PM 在 AM 时间触发

java - 只有一张 gwt-chart 可见

java - 为什么在这种简单情况下 notifyAll() 不恢复其他线程?

java - 为什么执行AsyncTask时不需要捕获TimeoutException?

android - AlarmManager 有时不唤醒手机 (XPERIA)

android - 将字符串转换为 ArrayList<String>

java - Android应用程序,连接未知的蓝牙设备

java - 使用Reactor作为任务执行器的正确方法

java - 当我在平板电脑上运行应用程序时,Android Studio 中的按钮看起来很乱