【问题标题】:Android converting of file to bitmap returns null alwaysAndroid将文件转换为位图总是返回null
【发布时间】:2016-04-26 13:18:36
【问题描述】:

我的应用程序中有一个现有的File,我想将其转换为带有选项的Bitmap。我有一个方法。但是这个方法总是返回 null,当我尝试获取位图的属性时,我会捕捉到NullPointerException。这是一个代码:

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。我能用它做什么?

【问题讨论】:

    标签: android bitmap bitmapfactory


    【解决方案1】:

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

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

    让我知道你是否还有问题 :) 快乐编码 :)

    【讨论】:

    • 感谢您的帮助。但是,不幸的是,我发现了 OutOfMemoryError :(
    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-02
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 2018-01-16
      • 2012-12-25
      • 1970-01-01
      相关资源
      最近更新 更多