How can I take a Drawable that I got from the internet and save it to my Android device in a cache directory?
android, android-file, drawable, eclipse, java
Solution
Use `Bitmap.compress(...)`, like so:
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream("/someLocation/someFileName.jpg"));
} catch (Exception e) {
//TODO: Handle exception
}
See this SO answer for an example on how to get your cache directory path:
android-download-images-from-server-and-save-them-on-device-cache
And this on conversion from `Drawable` to `Bitmap`:
how-to-convert-a-drawable-to-a-bitmap
Problem
Here is my code... you'll see where I want to save the `Drawable d` into the `File f` location: ``` ImageView imgView = (ImageView)header.findViewById(R.id.imvCover); File cacheDir = this.getCacheDir(); File f = new File(cacheDir, itemDict.get("Barcode") + ".jpg"); if (f.exists()) { Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath()); imgView.setImageBitmap(bmp); } else { String url = (String)itemDict.get("imageURL"); InputStream is = null; try { is = (InputStream) new URL(url).getContent(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Drawable d = Drawable.createFromStream(is, "src"); if (d != null) { imgView.setImageDrawable(d); // TODO: save the drawable into the cache directory } else { imgView.setImageResource(R.drawable.cam); } } ``` How do I save the Drawable as a .jpg?