简体   繁体   English

如何获取从 Internet 获得的 Drawable 并将其保存到我的 Android 设备的缓存目录中?

[英]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:这是我的代码...你会看到我想将Drawable d保存到File f位置的位置:

    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?如何将 Drawable 保存为 .jpg?

Use Bitmap.compress(...) , like so:使用Bitmap.compress(...) ,如下所示:

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:有关如何获取缓存目录路径的示例,请参阅此 SO 答案:

android-download-images-from-server-and-save-them-on-device-cache android-download-images-from-server-and-save-them-on-device-cache

And this on conversion from Drawable to Bitmap :这是从DrawableBitmap转换:

how-to-convert-a-drawable-to-a-bitmap 如何将可绘制对象转换为位图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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