3

这是我的代码...您将看到我要将其保存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?

4

1 回答 1

4

使用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

如何将可绘制的位图转换为位图

于 2012-11-13T00:21:53.293 回答