Android将文件转换为位图始终为空

问题描述:

我在我的应用程序中有一个现有的File,我想将它转换为带有选项的Bitmap。我有一个方法。但总是这个方法返回null,当我尝试获取位图的属性时,我抓到了NullPointerException。这里有一个代码:Android将文件转换为位图始终为空

public static Bitmap convertToBitmap(File file) { 
    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    options.inSampleSize = 4; 
    return BitmapFactory.decodeFile(file.getAbsolutePath(), options); 
} 

如果我删除选项,并呼吁BitmapFactory.decodeFile(file.getAbsolutePath())我会在某些设备上得到OutOfMemoryError。我该怎么办?

你可以试试下面的代码:)

final Uri uri= Uri.fromFile(new File(file)) 
    try{ 
     Bitmap selectedImageBitMap= MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri); 
     //you have your image bitmap :) 
     } 
    catch (FileNotFoundException fileNotFoundException){ 
     Log.d("sandeep","could not find file"); 
     } 
    catch(IOException ioexception) { 
     Log.d("sandeep", "IOException"); 
     } 

还是让我知道,如果你仍然有问题:)快乐编码:)

+1

感谢您的帮助。但是,不幸的是,我已经抓住OutOfMemoryError :( –

试试这个

BitmapFactory.Options bmOptions = new BitmapFactory.Options(); 
Bitmap bitmap =BitmapFactory.decodeFile(file.getAbsolutePath(),bmOptions); 
bitmap =Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);