Saving Image Retrieved from InputStream locally

与世无争的帅哥 提交于 2020-01-05 12:32:34

问题


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 = Drawable.createFromStream(is, "imagename");
    ImageView... 

Now I want to save this image (Drawable d) locally when a user clicks a button so I can display it again in another activity (along with a few other tasks).

I'd like to store it within the app folder itself rather than on the SD card.

How would I do this?

Thanks! Shannon


回答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);



回答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




回答3:


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




回答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);


来源:https://stackoverflow.com/questions/8012582/saving-image-retrieved-from-inputstream-locally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!