Reputation: 2862
I want lo load the image from url and save it in a file in sd card and then load from file and show on image view.
So I am trying to load image using picasso. But its not showing on image view.
Here is url:
http://xesoftwares.co.in/contactsapi/profile_images/d34b638b93773140eb94d5f03c20237c.jpg
Loading image using picasso.
Picasso.with(MainActivity.this).load(url).into(profileImage);
How to download the image from url. Save it in file in sd card and then load the image from file to show on image view?
Please help. Thank you..
Upvotes: 0
Views: 6679
Reputation: 1247
Add :
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
In your manifest file, otherwise the source cannot be downloaded.
If you want to save it in sd card you need another permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In order to save it.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
If you want to get that file in the future.
Next if you want to save it to an external directory, you can try this:
public void setUpDirectory(String folderName,String source){
File directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+folderName);
if(!directory.exists() && !directory.isDirectory()) {
directory.mkdirs();
}
URL imageurl = new URL(source);
Bitmap bitmap = BitmapFactory.decodeStream(imageurl.openConnection().getInputStream());
saveFile(directory,bitmap);
}
private void saveFile(File fileName,Bitmap bmp){
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outputStream ); // 100 will be ignored
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if outputStream != null) {
outputStream .close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 1
Reputation: 68
If you have put an image as background of ImageView in xml remove it.
Upvotes: 0
Reputation: 9056
Use GLIDE library it automatically store your image into Cache .....
Glide.with(context).load(url).into(profileImage);
Note:- Only first time you require internet for loading image. When Image load its working on without internet.
EDIT:- use this gradle
compile 'com.github.bumptech.glide:glide:3.7.0'
Output:-
Upvotes: 5
Reputation: 68
To save it into sd card you must declare uses permissions write read from sd card in manifest, also ask user for these permissions for android 5.0+. All this is documented clearly in android developers official website. Change MainActivity.class to getApplicationContext()
Upvotes: 0