使用Compressor库时发生java.lang.NullPointerException

时间:2019-07-14 13:59:09

标签: android image-processing nullpointerexception android-image image-compression

使用压缩程序库(https://github.com/zetbaitsu/Compressor)压缩图像时遇到问题
当我尝试使用Android-Image-Cropper(https://github.com/ArthurHub/Android-Image-Cropper)进行压缩时,一切正常, 但是当我使用

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);

错误

java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference

发生

1 个答案:

答案 0 :(得分:1)

您没有故意传递图像URI,因此它给出了NullPointerException

尝试一下:

Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
    f.createNewFile();
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
} catch (IOException e) {                       
        e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));

此代码节选自here