Convert a File Object to Bitmap

早过忘川 提交于 2020-02-26 07:48:17

问题


I am using Universal-Image-Loader and there is this functionality that access the file cache of the image from sd card. But I don't know how to convert the returned file cache into bitmap. Basically I just wanted to assign the bitmap to an ImageView.

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

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

Error: "The method setImageBitmap(Bitmap) in the type ImageView is not applicable for the arguments (File)"


回答1:


You should be able to use BitmapFactory:

File mSaveBit; // Your image file
String filePath = mSaveBit.getPath();  
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
mImageView.setImageBitmap(bitmap);



回答2:


  1. Define File

    String fileName = "/myImage.jpg";
    File file = new File(fileName); 
    
  2. get Bitmap of Image

    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    
  3. Set Bitmap to ImageView

    myImageView.setImageBitmap(bitmap);
    



回答3:


Here is a simple code to create a scaled image for ImageView in this case - Width:400 - Height: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));



回答4:


Kotlin Version

  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)
                }
            }
        }



回答5:


This is not the right question, but if you use flag .cacheInMemory() in ImageLoader setup you can retrive the bitmap without need of recreate at any time using BitmapFactory to safe memory usage .

Just use:

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



来源:https://stackoverflow.com/questions/19172154/convert-a-file-object-to-bitmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!