57

我正在使用 Universal-Image-Loader 并且有这个功能可以从 sd 卡访问图像的文件缓存。但我不知道如何将返回的文件缓存转换为位图。基本上我只是想将位图分配给 ImageView。

File mSaveBit = imageLoader.getDiscCache().get(easyPuzzle);

Log.d("#ImageValue: ", ""+mSaveBit.toString());
mImageView.setImageBitmap(mSaveBit);

错误:“ImageView 类型中的方法 setImageBitmap(Bitmap) 不适用于参数(文件)”

4

6 回答 6

166

您应该能够使用BitmapFactory

File mSaveBit; // Your image file
String filePath = mSaveBit.getPath();  
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
mImageView.setImageBitmap(bitmap);
于 2013-10-04T02:41:20.517 回答
14
  1. 定义文件

    String fileName = "/myImage.jpg";
    File file = new File(fileName); 
    
  2. 获取图像的位图

    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    
  3. 将位图设置为 ImageView

    myImageView.setImageBitmap(bitmap);
    
于 2015-06-05T05:45:12.123 回答
2

您可以使用此功能从文件路径获取位图

fun getBitmap(filePath:String):Bitmap?{
    var bitmap:Bitmap?=null
    try{
        var f:File = File(path)
        var options = BitmapFactory.Options()
        options.inPreferredConfig = Bitmap.Config.ARGB_8888
        bitmap = BitmapFactory.decodeStream(FileInputStream(f),null,options)
    }catch (e:Exception){

    }
    return bitmap
}
于 2021-01-15T21:55:11.617 回答
0

这是在这种情况下为 ImageView 创建缩放图像的简单代码 - 宽度:400 - 高度:400

final File file = new File(Environment.getExternalStorageDirectory(),"b.jpg");
ImageView img = (ImageView) findViewById(R.id.imageview);
img.setImageBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()),400,400,false));
于 2017-09-13T18:17:20.700 回答
0

Kotlin 版本

  if (requestCode==PICK_IMAGE_REQUEST){
            if (data!=null){
                selectedfileUri=data.data
                if (selectedfileUri!=null && !selectedfileUri!!.path.isEmpty()){
                    val file = FileUtils.getFile(context,selectedfileUri)
                    val bitmap = BitmapFactory.decodeFile(file.path)
                    uimg!!.setImageBitmap(bitmap)
                }
            }
        }
于 2018-10-11T02:53:08.457 回答
0

这不是正确的问题,但是如果您在 ImageLoader 设置中使用标志 .cacheInMemory() ,您可以随时使用 BitmapFactory 来检索位图而无需重新创建以保护内存使用。

只需使用:

Bitmap bitmap = ImageLoader.getInstance().getMemoryCache()·get("url as key");

于 2019-08-27T19:49:59.133 回答