4

I am using Asynctask to download a image from internet.

I want to save this image to internal storage and later I want to use this image.

I can download successfully but I cant find internal storage path where it is storing.

This DownloadImages.java

private class DownloadImages extends AsyncTask<String,Void,Bitmap> {

        private Bitmap DownloadImageBitmap(){
            HttpURLConnection connection    = null;
            InputStream is                  = null;

            try {
                URL get_url     = new URL("http://www.medyasef.com/wp-content/themes/medyasef/images/altlogo.png");
                connection      = (HttpURLConnection) get_url.openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.connect();
                is              = new BufferedInputStream(connection.getInputStream());
                final Bitmap bitmap = BitmapFactory.decodeStream(is);
               // ??????????

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                connection.disconnect();
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            return DownloadImageBitmap();
        }

    }

Any help will be appreciated. :)

Thank you.

Avijit
  • 3,834
  • 4
  • 33
  • 45
Olkunmustafa
  • 3,103
  • 9
  • 42
  • 55
  • 1
    possible duplicate of [Android Saving created bitmap to directory on sd card](http://stackoverflow.com/questions/4263375/android-saving-created-bitmap-to-directory-on-sd-card) – John Boker Nov 14 '13 at 12:52
  • You have got the bitmap `final Bitmap bitmap = BitmapFactory.decodeStream(is);` Use this bitmap for future use. What is the big deal? – Rethinavel Nov 14 '13 at 12:53
  • 1
    look at this answer http://stackoverflow.com/a/7887114/964741 – RajaReddy PolamReddy Nov 14 '13 at 12:56

6 Answers6

15

You can save and load the image on the internal storage like this: Saving:

public static void saveFile(Context context, Bitmap b, String picName){ 
    FileOutputStream fos; 
    try { 
        fos = context.openFileOutput(picName, Context.MODE_PRIVATE); 
        b.compress(Bitmap.CompressFormat.PNG, 100, fos);  
    }  
    catch (FileNotFoundException e) { 
        Log.d(TAG, "file not found"); 
        e.printStackTrace(); 
    }  
    catch (IOException e) { 
        Log.d(TAG, "io exception"); 
        e.printStackTrace(); 
    } finally {
        fos.close();
    }
}

Loading:

public static Bitmap loadBitmap(Context context, String picName){ 
    Bitmap b = null; 
    FileInputStream fis; 
    try { 
        fis = context.openFileInput(picName); 
        b = BitmapFactory.decodeStream(fis);   
    }  
    catch (FileNotFoundException e) { 
        Log.d(TAG, "file not found"); 
        e.printStackTrace(); 
    }  
    catch (IOException e) { 
        Log.d(TAG, "io exception"); 
        e.printStackTrace(); 
    } finally {
        fis.close();
    }
    return b; 
} 

But you will need to save the imageName somehow if you want to find it again if the app is closed. I would recomend an SQLLite database that map imageNames to entries in the database.

Vova
  • 956
  • 8
  • 22
Joakim Palmkvist
  • 540
  • 2
  • 11
1

Try this:

String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
String imageName = "yourImageName";
File file = new File(path, imageName);
try {
    fOut = new FileOutputStream(file);
    if (!yourBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fOut)) {
        Log.e("Log", "error while saving bitmap " + path + imageName);
    }
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Damien R.
  • 3,383
  • 1
  • 21
  • 32
1

My solution on Kotlin. (base on another answer)

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

class InternalStorageProvider(var context: Context) {

fun saveBitmap(bitmap: Bitmap, imageName: String) {
    var fileOutputStream: FileOutputStream? = null
    try {
        fileOutputStream = context.openFileOutput(imageName, Context.MODE_PRIVATE)
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        fileOutputStream?.close()
    }
}

fun loadBitmap(picName: String): Bitmap? {
    var bitmap: Bitmap? = null
    var fileInputStream: FileInputStream? = null
    try {
        fileInputStream = context.openFileInput(picName)
        bitmap = BitmapFactory.decodeStream(fileInputStream)
    } catch (e: FileNotFoundException) {
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        fileInputStream?.close()
    }

    return bitmap
}
}
Vova
  • 956
  • 8
  • 22
  • Can you explain how are you initialising this class? I have issues when calling this class with `InternalStorageProvider(context).saveBitmap(bitmap, filename)`. Am I doing anything wrong? – besthiroeu Jan 23 '18 at 20:00
  • Please, provide some details. Do you try the following code in Activity, Fragment or another class – Vova Jan 23 '18 at 20:17
  • I'm calling this class from fragment. If I put this code inside fragment it works. This is kinda wierd issue because for some reason I cannot import this class to fragment: `import com.packagename... helpers.InternalStorageProvider` is unresolved. Tho if I remove context constructor import works. – besthiroeu Jan 25 '18 at 06:52
  • Guess so, works inside fragment. Anyway I'm gonna explore this later, I was just wondering is my syntax fine and It looks to be. I'm still new to Kotlin and atm I'm rewriting my code from Java to Android.. – besthiroeu Jan 25 '18 at 13:24
1

Have you considered using Glide library (or Picasso) to download images? That way you abstract all the low-level details of Http connections, disk saving, memory and disk cache, offline capabilities, etc. Also, if you choose Glide, you automatically gain some neat fading in animations on image loading.

Examples (kotlin)

To download to disk:

Glide.with(applicationContext)
   .load(user.picUrl)
   .downloadOnly(object : SimpleTarget<File>() {
      override fun onResourceReady(res: File, glideAnimation: GlideAnimation<in File>) {}
   })

To load from cache, or download if not available on cache:

Glide.with(callingActivity.applicationContext)
   .load(wallPostViewHolder.mUser!!.picUrl)
   .skipMemoryCache(true)
   .diskCacheStrategy(DiskCacheStrategy.SOURCE)
   .into(wallPostViewHolder.vPic)
Patrick Steiger
  • 184
  • 2
  • 11
0

When you are programming this and running the app, sometimes is necessary to uninstall the app from your emulator/phone (in case where you have defined a file as folder, and you corrected that, but in the memory of the emulator/phone still as folder)

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Rodrigo João Bertotti
  • 5,179
  • 2
  • 23
  • 34
0

If you are using kotlin then use below function. you have to provide a path for storing image, a Bitmap (convert your image and then pass that bitmap to this function) and if you want to decrease the quality of the image then provide %age i.e 10%.

fun cacheToLocal(localPath: String, bitmap: Bitmap, quality: Int = 100) {
        val file = File(localPath)
        file.createNewFile()
        val ostream = FileOutputStream(file)
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, ostream)
        ostream.flush()
        ostream.close()
    }