【问题标题】:How can I take a Drawable that I got from the internet and save it to my Android device in a cache directory?如何获取从 Internet 获取的 Drawable 并将其保存到我的 Android 设备的缓存目录中?
【发布时间】:2012-11-13 00:11:29
【问题描述】:

这是我的代码...您将看到我要将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);
        }
    }   

如何将 Drawable 保存为 .jpg?

【问题讨论】:

    标签: java android eclipse drawable android-file


    【解决方案1】:

    使用Bitmap.compress(...),像这样:

    try {
       bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream("/someLocation/someFileName.jpg"));
    } catch (Exception e) {
       //TODO: Handle exception
    }
    

    有关如何获取缓存目录路径的示例,请参阅此 SO 答案:

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

    这是从DrawableBitmap 的转换:

    how-to-convert-a-drawable-to-a-bitmap

    【讨论】:

    • 这是一个位图。来自 Drawable 呢?查看我的代码。
    • @Ethan Allen。将 Drawable 转换为位图。请参阅编辑后的答案。
    • 是的,刚刚找到:Bitmap bitmap = ((BitmapDrawable)d).getBitmap(); - 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多