I'm setting an ImageView using setImageBitmap
with an external image url. I would like to save the image so it can be used later on even if there is no internet connection. Where and how can I save it?
Asked
Active
Viewed 3.5k times
4

Amit
- 1,174
- 2
- 15
- 22
5 Answers
5
You have to save it in SD card or in your package data, because on runtime you only have access to these. To do that this is a good example
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 (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();
}
Source : How do I transfer an image from its URL to the SD card?

Community
- 1
- 1

Sarim Sidd
- 2,166
- 2
- 22
- 31
-
This code will not compile. `Environment.getExternalStorageDirectory()` does not return a `String`. – Jeff Axelrod Aug 10 '12 at 20:28
-
3What is aReasonableSize – Ruchit Shah Jul 10 '15 at 07:55
-
Exactly! what is aReasonableSize? – Steve Kamau Sep 17 '16 at 06:56
-
I guess we'll never know – Denny Oct 18 '18 at 19:10
-
1@Denny aReasonableSize can be1024 and 2048. – Sarim Sidd Oct 23 '18 at 09:43
-
1It's the buffer size (a.k.a. the quantity of bytes to be read/write at a time). The bigger the buffer size, more chunk of data will be read/written. – Van May 24 '19 at 18:19
1
If you are using Kotlin and Glide in your app then this is for you:
Glide.with(this)
.asBitmap()
.load(imageURL)
.into(object : SimpleTarget<Bitmap>(1920, 1080) {
override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap>?) {
saveImage(bitmap)
}
})
and this is that function
internal fun saveImage(image: Bitmap) {
val savedImagePath: String
val imageFileName = System.currentTimeMillis().toString() + ".jpg"
val storageDir = File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString() + "/Folder Name")
var success = true
if (!storageDir.exists()) {
success = storageDir.mkdirs()
}
if (success) {
val imageFile = File(storageDir, imageFileName)
savedImagePath = imageFile.absolutePath
try {
val fOut = FileOutputStream(imageFile)
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut)
fOut.close()
} catch (e: Exception) {
e.printStackTrace()
}
galleryAddPic(savedImagePath)
}
}
private fun galleryAddPic(imagePath: String) {
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
val f = File(imagePath)
val contentUri = FileProvider.getUriForFile(applicationContext, packageName, f)
mediaScanIntent.data = contentUri
sendBroadcast(mediaScanIntent)
}
galleryAddPic()
is used to see the image in a phone gallery.
Note: now if you face file uri exception then this can help you.

Kishan Solanki
- 13,761
- 4
- 85
- 82
0
you can save image in sdcard and you can use that image in future without internet.
see this tutorial will show how to store image and again read it.
Hope this will help you.....!

MAC
- 15,799
- 8
- 54
- 95
0
May be its will help someone like me one day
new SaveImage().execute(mViewPager.getCurrentItem());//calling function
private void saveImage(int currentItem) {
String stringUrl = Site.BASE_URL + "socialengine/" + allImages.get(currentItem).getMaster();
Utils.debugger(TAG, stringUrl);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(stringUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
String fileName = stringUrl.substring(stringUrl.lastIndexOf('/') + 1, stringUrl.length());
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
File imgFile = new File(sdCardRoot, "IMG" + System.currentTimeMillis() / 100 + fileName);
if (!sdCardRoot.exists()) {
imgFile.createNewFile();
}
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
FileOutputStream outPut = new FileOutputStream(imgFile);
int downloadedSize = 0;
byte[] buffer = new byte[2024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
outPut.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Utils.debugger("Progress:", "downloadedSize:" + Math.abs(downloadedSize*100/totalSize));
}
outPut.close();
//if (downloadedSize == totalSize);
//Toast.makeText(context, "Downloaded" + imgFile.getPath(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
private class SaveImage extends AsyncTask<Integer, Void, String> {
@Override
protected String doInBackground(Integer... strings) {
saveImage(strings[0]);
return "saved";
}
@Override
protected void onPostExecute(String s) {
Toast.makeText(context, "" + s, Toast.LENGTH_SHORT).show();
}
}

Aklesh Singh
- 917
- 10
- 12