简体   繁体   中英

How to access image downloaded from the web

I downloaded an image from the web using this code and saved it directly to the application specific internal storage.

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);

How do I access this stored image using Drawable ? I attempted to open it using the following code but the operation resulted in a file not found exception.

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

Assuming you call os.close() in the following lines of your code

You need to specify the path when instantiating your File object. Do the following :

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

As said in doc of getFilesDir() method :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM