Download image from server and store it on SD card
Use an async task to download and save images to external storage.
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
System.out.println("Starting download");
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString();
System.out.println("Downloading");
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream(root+"/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* After completing background task
* **/
@Override
protected void onPostExecute(String file_url) {
System.out.println("Downloaded");
}
}
You just call the above class using
new DownloadFileFromURL().execute(<The url you want to download from>);
You will also need to add below permissions to Manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Hope it helps
load image from URL and save on memory in android
Try to use this code:
Method for loading image from imageUrl
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And You should use it in a separate thread, like that:
new Thread(new Runnable() {
@Override
public void run() {
try {
Bitmap bitmap = getBitmapFromURL(<URL of your image>);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
But using Picasso - indeed a better way.
Update:
For saving Bitmap
to file on external storage (SD card) You can use method like this:
public static void writeBitmapToSD(String aFileName, Bitmap aBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
File sdPath = Environment.getExternalStorageDirectory();
File sdFile = new File(sdPath, aFileName);
if (sdFile.exists()) {
sdFile.delete ();
}
try {
FileOutputStream out = new FileOutputStream(sdFile);
aBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
Remember that You need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
for it.
And for loading `Bitmap` from file on external storage You can use method like that:
public static Bitmap loadImageFromSD(String aFileName) {
Bitmap result = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), aFileName));
result = BitmapFactory.decodeStream(fis);
fis.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "loadImageFromSD: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You need
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to do this.
Update 2
Method getBitmapFromURL()
, but ImageView
should be updated from UI thread, so You should call getBitmapFromURL()
, for example, this way:
new Thread(new Runnable() {
@Override
public void run() {
try {
final Bitmap bitmap = getBitmapFromURL("<your_image_URL>");
runOnUiThread(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
How do I transfer an image from its URL to the SD card?
First you must make sure your application has permission to write to the sdcard. To do this you need to add the uses permission write external storage in your applications manifest file. See Setting Android Permissions
Then you can you can download the URL to a file on the sdcard. A simple way is:
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,"myImage.png"));
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
EDIT :
Put permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
How to Save Internet Image with url in SD card (Android Kotlin)
Change the parameter type in
override fun onPostExecute(result: Void)
to
override fun onPostExecute(result: Void?)
.
And as Akhilesh Kumar mentioned here you should also change
class SaveThisImage : AsyncTask<Void, Void, Void>()
to
class SaveThisImage : AsyncTask<Void, Void, Void?>()
This is because the doInBackground
in your code returns a nullable type Void?
. The return value of doInBackground
is passed as an argument to onPostExcecute
but your onPostExecute
accepts a non null value Void
instead of a nullable one Void?
.
As a side-note you should use Unit
instead of Void
when in Kotlin
EDIT
To make your saved image appear the media database needs to be updated. The media database is updated when you restart your device or after some time passes it will show up in the save location. To update the media database immediately you can use the MediaScannerConnection
object.
Try passing your saved file to this function after bitmap.compress
and pass your myImageFile
/**
* Updates the Pictures gallery to include the newly created file.
* @param fileObj: file path to be scanned so that the new file will appear in the gallery
*/
private fun refreshPhoneGallery(fileObj: File)
{
/* Scan the specified file path so that the new file will appear in gallery */
MediaScannerConnection.scanFile(
yourContext,
arrayOf(fileObj.path),
null,
object : MediaScannerConnection.OnScanCompletedListener
{
override fun onScanCompleted(scannedFilePath: String?, p1: Uri?)
{
// Do whatever
}
}
)
}
Android - Saving a downloaded image from URL onto SD card
You will need to first create the directories and sub-directories where you want to create the files.
I see that you used the mkdir() method. Try mkdirs(), and it should work.
Download image from firebase to external sd Card using url
first of all create database ref and a File like this
StorageReference downloadRef = FirebaseStorage.getInstance().getReference().child("Wall/" + category
+ "/" + wall_id + ".jpg");
File localFile = null;
try {
String fileName = wall_id + ".jpg";
localFile = new File();//create your file with desired path
} catch (Exception e) {
e.printStackTrace();
}
than call getFile on that reference like this
downloadRef.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
dialog.dismiss();
}
}).addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onProgress(FileDownloadTask.TaskSnapshot taskSnapshot) {}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Toast.makeText(WallOptionActivity.this, "Download failed!", Toast.LENGTH_SHORT).show();
}
});
the file will be saved to given path.
Related Topics
How to Have the Code Pause for a Couple of Seconds in Android
Urlconnection Getcontentlength() Is Returning a Negative Value
Android Gives Error "Cannot Fit Requested Classes in a Single Dex File"
How to Check If Class Exists Somewhere in Package
What Does '->' (Arrow) Mean in Gradle's Dependency Graph
What Is the Use of Memoryfile in Android
How to Script the Java Debugger Command-Line Tool (Jdb)
What's the Equivalent of Java's Thread.Sleep() in JavaScript
How to Set -Source 1.7 in Android Studio and Gradle
Can't Run Junit 4 Test Case in Eclipse Android Project
Cannot Resolve Method Getmap()
Preload Multiple Images with Glide
How to Change Method Behaviour Through Reflection
Recyclerview Painfully Slow to Load Cached Images Form Picasso
Spannable on Android for Textview