如何在 Kotlin 中将 res 中的 ImageView 转换为 Base64 字符串

How to convert ImageView in res to Base64 String, in Kotlin

我想请求 Flask 服务器。 所以,我在 Kotlin(Android Studio)

中将 img 转换为 JSON 数据

虽然JSON数据从服务器发送和接收都很好,但传输数据的大小是原始数据的五倍。

我应该怎么做才能从服务器获取准确的数据?

简单服务器代码(python)...

    print(len(request.json['file']))
    img_data = base64.b64decode(request.json['file'])
    filename = 'received_now_starry_night.png'
    with open(filename, 'wb') as f:
        f.write(img_data)


    dic = {
        "msg":"hello"
    }
    return jsonify(dic)

Android工作室,kotlin代码...

   val bitmap:Bitmap = BitmapFactory.decodeResource(resources, R.drawable.starry_night)
   val bos:ByteArrayOutputStream = ByteArrayOutputStream()
   bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos)
   val image:ByteArray = bos.toByteArray()

   val base64Encoded = java.util.Base64.getEncoder().encodeToString(image)

   val rootObject = JSONObject()
   rootObject.put("file", base64Encoded)

将图像转换为 Base64 字符串:

您还可以创建调整大小的位图并压缩它以减小尺寸

    private fun CreateImageStringFromBitmap(): String {

        val bitmap:Bitmap = BitmapFactory.decodeResource(resources, R.drawable.starry_night)

        val resized = Bitmap.createScaledBitmap(
            bitmap:Bitmap, (desired width).toInt(),
            (desired height).toInt(), true
        )

        val stream = ByteArrayOutputStream()
        resized.compress(Bitmap.CompressFormat.PNG, 75, stream)
        val byteArray: ByteArray = stream.toByteArray()

        return Base64.encodeToString(byteArray, Base64.DEFAULT)
    }