【问题标题】:How to fix null error in getWidth() on bitmap [duplicate]如何修复位图上getWidth()中的空错误[重复]
【发布时间】:2026-01-31 13:50:01
【问题描述】:

在我的应用程序中,我想从 图库 中选择图像并压缩它。
对于压缩我使用这个库:https://github.com/zetbaitsu/Compressor

我为它写了下面的代码,但是当我运行应用程序并从图库中选择图像时,它会抛出 force close 并在 logCat 中显示以下错误:

我的活动代码:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) {
                if (data != null) {
                    // Get the Image from data
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};

                    Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    assert cursor != null;
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    mediaPath = cursor.getString(columnIndex);
                    cursor.close();

                    postPath = mediaPath;
                    uploadImageToServer(postPath);
                }

            }
        } else if (resultCode != RESULT_CANCELED) {
        }
    }
}
    private void uploadImageToServer(String imagePath) {
        if (imagePath == null || imagePath.equals("")) {
            return;
        } else {
            showpDialog();
            Map<String, RequestBody> map = new HashMap<>();
            File file = new File(imagePath);
            try {
                compressedImage = new Compressor(getActivity())
                        .setMaxWidth(2000)
                        .setMaxHeight(1400)
                        .setQuality(90)
                        .setCompressFormat(Bitmap.CompressFormat.JPEG)
                        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                Environment.DIRECTORY_PICTURES).getAbsolutePath())
                        .compressToFile(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
}

LogCat 错误:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
                                                                       at id.zelory.compressor.ImageUtil.decodeSampledBitmapFromFile(ImageUtil.java:70)
                                                                       at id.zelory.compressor.ImageUtil.compressImage(ImageUtil.java:33)
                                                                       at id.zelory.compressor.Compressor.compressToFile(Compressor.java:60)
                                                                       at id.zelory.compressor.Compressor.compressToFile(Compressor.java:56)
                                                                       at com.app.android.Fragments.NewAddressFragment.uploadImageToServer(NewAddressFragment.java:486)
                                                                       at com.app.android.Fragments.NewAddressFragment.onActivityResult(NewAddressFragment.java:353)
                                                                       at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:156)
                                                                       at android.app.Activity.dispatchActivityResult(Activity.java:7295)

显示此行的错误: .compressToFile(file);

更新:仅针对某些图像显示此错误,而不是所有图像! 我该如何解决?请帮帮我

【问题讨论】:

  • 这是因为你生成的Bitmap是空的。
  • @VirRajpurohit,仅针对某些图像显示此错误,而不是所有图像!我该如何解决?你能帮帮我吗?
  • 检查哪个变量为空,要么实例化它,要么中止进程
  • 有些图片需要识别,因为URI可能有问题。
  • @Stultuske,你能发给我看看我该怎么做吗?请

标签: java android nullpointerexception compression android-bitmap


【解决方案1】:

GitHub 的另一个假设是,您可能会尝试将更改后的文件以原始名称存储在原始路径中。这也可能导致问题。请尝试此版本的代码。我加了compressedFileName

private void uploadImageToServer(String imagePath) {
        if (imagePath == null || imagePath.equals("")) {
            return;
        } else {
            showpDialog();
            Map<String, RequestBody> map = new HashMap<>();
            File file = new File(imagePath);

            if(file != null && file.exists() && file.canRead()) {
                try {
                    String compressedFileName = "_" + file.getName();

                    compressedImage = new Compressor(getActivity())
                            .setMaxWidth(2000)
                            .setMaxHeight(1400)
                            .setQuality(90)
                            .setCompressFormat(Bitmap.CompressFormat.JPEG)
                            .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                    Environment.DIRECTORY_PICTURES).getAbsolutePath())
                            .compressToFile(file, compressedFileName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
}

【讨论】:

  • 请注意,新文件名有一个额外的下划线。 compressedFileName = "_" + file.getName();.
  • 非常糟糕!再次显示错误!为什么yyyyyyy? :( :(
  • 对不起,但我没有更多的想法。 android 本身不是我的一杯茶...
  • 非常感谢您的帮助和时间,谢谢亲爱的
【解决方案2】:

请通过 try 和 catch 块处理并向用户显示对话框消息以选择另一个图像,可能是所选图像已损坏。

【讨论】:

    【解决方案3】:

    只要确保该文件不为空即可。

    private void uploadImageToServer(String imagePath) {
            if (imagePath == null || imagePath.equals("")) {
                return;
            } else {
                showpDialog();
                Map<String, RequestBody> map = new HashMap<>();
                File file = new File(imagePath);
    
                if(file != null && file.exists() && file.canRead()) {
                    try {
                        compressedImage = new Compressor(getActivity())
                                .setMaxWidth(2000)
                                .setMaxHeight(1400)
                                .setQuality(90)
                                .setCompressFormat(Bitmap.CompressFormat.JPEG)
                                .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                        Environment.DIRECTORY_PICTURES).getAbsolutePath())
                                .compressToFile(file);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
            }
    }
    

    【讨论】:

    • 再次显示错误:(
    • 对不起,我的错。这仍然只是一个路径检查。我只是扩展了 if 子句。它现在检查文件本身是否存在。请重试。
    • 又不行了!为什么给我看错误!我运气不好
    • 还是同样的错误?还是其他类型的错误?
    • 再次显示上述错误!