How can I convert an image into a Base64 string?

前端 未结 14 1198
离开以前
离开以前 2020-11-22 06:52

What is the code to transform an image (maximum of 200 KB) into a Base64 String?

I need to know how to do it with Android, because I have to add the functionali

14条回答
  •  长发绾君心
    2020-11-22 07:00

    Here is the encoding and decoding code in Kotlin:

     fun encode(imageUri: Uri): String {
        val input = activity.getContentResolver().openInputStream(imageUri)
        val image = BitmapFactory.decodeStream(input , null, null)
    
        // Encode image to base64 string
        val baos = ByteArrayOutputStream()
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        var imageBytes = baos.toByteArray()
        val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
        return imageString
    }
    
    fun decode(imageString: String) {
    
        // Decode base64 string to image
        val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
        val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
    
        imageview.setImageBitmap(decodedImage)
    }
    

提交回复
热议问题