3

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?

Ethan Allen
  • 14,425
  • 24
  • 101
  • 194

1 Answers1

4

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

Community
  • 1
  • 1
Gunnar Karlsson
  • 28,350
  • 10
  • 68
  • 71