首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我怎样才能把从互联网上得到的可抽屉保存到我的Android设备的缓存目录中呢?

我怎样才能把从互联网上得到的可抽屉保存到我的Android设备的缓存目录中呢?
EN

Stack Overflow用户
提问于 2012-11-13 08:11:29
回答 1查看 825关注 0票数 3

这是我的代码。您将看到我希望将Drawable d保存到File f位置的位置:

代码语言:javascript
运行
复制
    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);
        }
    }   

如何将可绘制文件另存为.jpg?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-13 08:21:53

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

代码语言:javascript
运行
复制
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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13353735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档