简体   繁体   中英

How can I take a Drawable that I got from the internet and save it to my Android device in a cache directory?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM