【问题标题】:BitmapFactory.decodeFile returns nullBitmapFactory.decodeFile 返回 null
【发布时间】:2016-10-17 12:54:44
【问题描述】:

我将使用Bitmap.compress() 方法压缩图像。

但是当我使用bitmap = BitmapFactory.decodeFile() 得到Bitmap 时,我得到了一个null 对象,并且该方法没有出现任何异常。

这是我的代码

public static File compressImage(String imagePath) throws IOException {

    // Get bitmap
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);

    // Get bitmap output stream
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);

......

当代码在最后一行运行时,我得到一个NullPointerException

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference

然后我在调试模式下运行我的代码,结果我从BitmapFactory.decodeFile 方法中得到了一个null 对象。

参数imagePath

/storage/emulated/0/DCIM/Camera/IMG_20160610_195633.jpg

看起来还可以。

这段代码在另一个活动中运行良好,但是当我将它复制到我尝试压缩和上传图像的异步线程时,它崩溃了。有没有可能这是因为异步线程的事情?还是我没有注意到的其他东西?

【问题讨论】:

    标签: android bitmap bitmapfactory


    【解决方案1】:

    从您的代码中删除以下内容:

    options.inJustDecodeBounds = true;
    

    来自inJustDecodeBounds的文档:

    如果设置为 true,解码器将返回 null(无位图),但 out... 字段仍将被设置,允许调用者查询 位图无需为其像素分配内存。

    inJustDecodeBounds 有助于有效地加载大的Bitmaps,因为您无需为它们分配内存即可读取它们的尺寸,尽管它在您的代码中没有任何用途。

    【讨论】:

      【解决方案2】:

      如果您使用通过 USB 连接的手机来调试代码,则此答案适用。我的手机显示安卓6.0.1版本。

      我阅读了所有关于设置“使用权限”字段的帖子,但我的代码仍然无法正常工作。但是,我发现我需要在“设置->设备->应用程序->应用程序管理器”下进入我的设备,然后单击我正在调试的应用程序并导航到“权限”并手动启用请求的权限。

      以下权限必须在您的 AndroidManifest.xml 中

      <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      

      【讨论】:

        猜你喜欢
        • 2018-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多