问题
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