Kotlin:如何将图像Uri转换为Bitmap以及Base64

时间:2019-06-28 17:12:12

标签: android kotlin

我在Java中找到了很多与此相关的答案,据说Kotlin解决方案与Java非常相似,但是在许多其他方面,魔鬼在细节上,还有一些。

我正在使用的SQLite数据库中有多个Uris存储,现在我想将此图像发送到API,该API会将它们与其他数据一起捕获。我将通过POST发送信息。

现在,我要加载Uri,就像使用ImageView.setImageURI()来加载Uri一样,将Uri转换为Bitmap并将其放置在ImageView容器中。

如何使用Kotlin代码将该Uri转换为Bitmap对象,然后将其编码为Base64,以将其发送到API?


编辑

我正在尝试使用Anupam的imageFileToBase64(),这似乎正是我想要的,现在我遇到了问题,我得到了FileNotFoundException。这就是我在做什么。

我从数据库中恢复了Uri字符串,该字符串的内容为:content:// media / external / images / media / 109,所以我将其转换为Uri

val uri = Uri.parse(uri_string)

然后我得到真实的路径,并将其转换为File

val file = File(uri.path)

最后我调用该函数

val base64 = imageFileToBase64(file)

我同时尝试了uri.pathuri.toString()并获得了相同的结果。

uri.path = / external / images / media / 109

uri.toString() =内容:/ media / external / images / media / 109

所以我不知道该向函数传递什么。

1 个答案:

答案 0 :(得分:1)

这些是用于以下目的的Kotlin方法-
1.从资产中获取位图
2.将位图保存到文件中
3.从位图获取Base64
4.将文件/图像编码为Base64
 5.将Base64解码为文件/图像

 // Get the bitmap from assets and display into image view
    val bitmap = assetsToBitmap("tulip.jpg")
    // If bitmap is not null
    bitmap?.let {
        image_view_bitmap.setImageBitmap(bitmap)
    }


    val imagePath = "C:\\base64\\image.png"

    // Encode File/Image to Base64
    val base64ImageString = encoder(imagePath)
    println("Base64ImageString = $base64ImageString")

    // Decoder Base4 to File/Image
    decoder(base64ImageString, "C:\\base64\\decoderImage.png")

    // Click listener for button widget
    button.setOnClickListener{
        if(bitmap!=null){
            // Save the bitmap to a file and display it into image view
            val uri = bitmapToFile(bitmap)
            image_view_file.setImageURI(uri)

            // Show a toast message
            toast("Bitmap saved in a file.")
        }else{
            toast("bitmap not found.")
        }
    }
}


// Method to get a bitmap from assets
private fun assetsToBitmap(fileName:String):Bitmap?{
    return try{
        val stream = assets.open(fileName)
        BitmapFactory.decodeStream(stream)
    }catch (e:IOException){
        e.printStackTrace()
        null
    }
}


// Method to save an bitmap to a file
private fun bitmapToFile(bitmap:Bitmap): Uri {
    // Get the context wrapper
    val wrapper = ContextWrapper(applicationContext)

    // Initialize a new file instance to save bitmap object
    var file = wrapper.getDir("Images",Context.MODE_PRIVATE)
    file = File(file,"${UUID.randomUUID()}.jpg")

    try{
        // Compress the bitmap and save in jpg format
        val stream:OutputStream = FileOutputStream(file)
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream)
        stream.flush()
        stream.close()
    }catch (e:IOException){
        e.printStackTrace()
    }

    // Return the saved bitmap uri
    return Uri.parse(file.absolutePath)
}

// Method to get Base64 from bitmap
private fun imageFileToBase64(imageFile: File): String {

 return FileInputStream(imageFile).use { inputStream ->
    ByteArrayOutputStream().use { outputStream ->
        Base64OutputStream(outputStream, Base64.DEFAULT).use { base64FilterStream ->
            inputStream.copyTo(base64FilterStream)
            base64FilterStream.flush()
            outputStream.toString()
          }
       }
   }
}


// Encode File/Image to Base64   
private fun encoder(filePath: String): String{
 val bytes = File(filePath).readBytes()
 val base64 = Base64.getEncoder().encodeToString(bytes)
return base64
}


// Decode Base64 to File/Image
private fun decoder(base64Str: String, pathFile: String): Unit{
  val imageByteArray = Base64.getDecoder().decode(base64Str)
  File(pathFile).writeBytes(imageByteArray)
}
相关问题