java - 方法'布尔 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()
}
}
解决方案
我敢打赌,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)
还要确保在工作线程中做这些事情。
推荐阅读
- iis - 并发 webApi 调用仅停留在 prod env 上
- python - 如何移动到 tkinter 对象或特定坐标
- bash - 使用 bash 更新配置文件特定部分中定义的值
- python - 在python中删除csv文件的第一行
- css - Firefox 没有使用 userChrome.css 文件获得全屏
- flask - Celery/Flask/Redis - apply_async 函数不起作用 - 更新 2
- angular - 如何在 Angular ES6 Observer 函数中使用多个语句?
- asp.net - 基本的自定义 Http Handler 甚至没有被执行
- c# - C#:填充 XML 文件
- python - 对于长时间运行的任务,推荐的 dask-kubernetes 配置覆盖是什么?