【问题标题】:Convert Uri to Bitmap将 Uri 转换为位图
【发布时间】:2021-04-07 11:22:22
【问题描述】:

我想将 Uri 从 .takePicture 方法转换为位图以供以后使用,我搜索了不同的方法,但每个方法都给我一个错误,说位图为空,有时“int android.graphics.bitmap.getwidth( )' 在空对象引用上"。


var imageUri:Uri?=null
    private fun takePhoto() {

        val photofile = File(externalMediaDirs.firstOrNull(), "picture - ${System.currentTimeMillis()}.jpg")
        val output = ImageCapture.OutputFileOptions.Builder(photofile).build()
        var image_View = findViewById<ImageView>(R.id.imageView)

        imageCapture?.takePicture(output, ContextCompat.getMainExecutor(this), object : ImageCapture.OnImageSavedCallback {
            override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                Toast.makeText(applicationContext, "Pic saved.", Toast.LENGTH_LONG).show()
                imageUri = outputFileResults.savedUri
                //image_View.setImageURI(imageUri)
            }

            override fun onError(exception: ImageCaptureException) {
                Toast.makeText(applicationContext, "Error saving pic!", Toast.LENGTH_LONG).show()
            }
        })
}

【问题讨论】:

    标签: android kotlin uri android-bitmap android-image


    【解决方案1】:

    试试这个sn-p

            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    

    【讨论】:

    • 当我尝试这个时,我的应用程序崩溃了,并且 getBitmap 也被划掉了。
    • 你能告诉我堆栈跟踪吗?
    【解决方案2】:

    引用the documentation for getSavedUri():

    仅当 ImageCapture.OutputFileOptions 由使用 #Builder(ContentResolver, Uri, ContentValues) 构造的 MediaStore 支持时才返回此字段

    这不是您用于OutputFileOptions 的构造函数。所以,检查getSavedUri() 是否返回null。如果是,您将需要使用photofile,包括采取措施将其保存为已保存的实例状态Bundle

    如果getSavedUri() 返回非null 值,您可能需要编辑您的问题并提供与您的崩溃相关的完整堆栈跟踪(而不是使用pastebin)。

    【讨论】:

      猜你喜欢
      • 2014-03-26
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多