Skip to content Skip to sidebar Skip to footer

Saving Image Retrieved From Inputstream Locally

I used the following code to retrieve an image from a url and display it within an activity. InputStream is = (InputStream) new URL(url[0]).getContent(); Drawable d = Drawa

Solution 1:

This will do it for you:

Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
FileOutputStream out = openFileOutput(filename, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);

Solution 2:

For Drawable save as image, I am doing this,

Bitmap image_saved=BitmapFactory.decodeResource(context.getResources(),R.drawable.icon);

FileOutputStream fOut=new FileOutputStream(path+"/"+fileName); 
// Here path is either sdcard or internal storage
image_saved.compress(Bitmap.CompressFormat.JPEG,100,fOut);
fOut.flush();
fOut.close();
image_saved.recycle(); // If no longer used..

But Actually, I suggest you to Instead of going from an InputStream to a Drawable, go from an InputStream to a File, then load the image out of the file. So you can save first file and use it in loading Image.

And for url Inputstream to write file look at this tutorial Save binary file from URL

Solution 3:

Please view this documentation for how to save cached files and this documentation for general internal file storage.

Solution 4:

Tested snippet :

InputStream is=null;
            try {
                is = (InputStream) new URL(url).getContent();
            } catch (MalformedURLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Drawable d = Drawable.createFromStream(is, "profile_picture");
            Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
            FileOutputStream out=null;
            try {
                out = getActivity().getApplicationContext().openFileOutput("profile_picture", getActivity().getApplicationContext().MODE_PRIVATE);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);

Post a Comment for "Saving Image Retrieved From Inputstream Locally"