首页 > 解决方案 > 方法'布尔 android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)

问题描述

我的代码中出现此错误,有人告诉我如何解决?感谢所有可以提供帮助的人。

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
        at map.app.fragments.ReportFragment.putImgToBytearray(ReportFragment.kt:177)

线路错误

bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream)

代码

private fun putImgToBytearray(): ByteArray {
    val stream = ByteArrayOutputStream()
    val drawable = this.imgThumb!!.drawable as BitmapDrawable
    val bitmap = drawable.bitmap
    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream)
    return stream.toByteArray()
}

onActivityResult 代码

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK) {


        try {

            //Getting the Bitmap from Gallery
            val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, this.imageUri) as Bitmap?
            this.imgThumb!!.setImageBitmap(bitmap)
            this.pictureTaken = true
        } catch (e:IOException) {
            e.printStackTrace()
        }
    } else {
        Toast.makeText(context, "Error loading image", Toast.LENGTH_LONG)
    }
}

从图库中选择图像的方法。这只是一种适应

fun openCamera() {
    try {
        val imageFile = createImageFile()
        val callCameraIntent =  Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if(callCameraIntent.resolveActivity(activity.packageManager) != null) {
            val authorities = activity.packageName + ".fileprovider"
            this.imageUri = FileProvider.getUriForFile(context, authorities, imageFile)
            callCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
            startActivityForResult(callCameraIntent, IMAGE_PICK_CODE)
        }
    } catch (e: IOException) {
        Toast.makeText(context, "Could not create file!", Toast.LENGTH_SHORT).show()
    }
}

标签: javaandroidkotlinbitmap

解决方案


我敢打赌,MediaStore.Images.Media.getBitmap它没有正确获取位图并返回 null。

因此,如果您删除?inMediaStore.Images.Media.getBitmap(context.contentResolver, this.imageUri) as Bitmap?您将得到一个运行时异常,正如您之前的问题所断言的那样。

所以将演员更改为:

MediaStore.Images.Media.getBitmap(context.contentResolver, this.imageUri) as Bitmap

确保您永远不会得到空位图,然后返回调查getBitmap方法

我不知道该createImageFile方法有什么作用,但我建议您简单地执行以下操作来测试它是否有效:

MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse("file://"+uri));

最后,我建议不要使用 of MediaStore.Images.Media.getBitmap

请参阅它已弃用。切换到图像加载库或使用ImageDecoder#createSource(ContentResolver, Uri)

提到的链接中有指南。像这个:

public static Bitmap decodeBitmap (ImageDecoder.Source src)

还要确保在工作线程中做这些事情。


推荐阅读