How to convert an image into base64 and also compress it using kotlin in androidX?

假如想象 提交于 2020-02-08 10:00:32

问题


I am creating an offline SMS app. I want to know how to convert image, chosen by the user, into string base64 and also compressed it.

I have searched a lot but not much material I found.All the data I found is in Java. But I need in Kotlin language.

Activity File

class MainActivity1 :AppCompatActivity(){

    private val requestReceiveSms: Int = 1
    private val requestSendSms: Int = 2
    private var mMessageRecycler: RecyclerView? = null
    private var mMessageAdapter: MessageAdapter? = null

    val SELECT_PICTURE = 5

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn1.setOnClickListener {
            dispatchGalleryIntent()
        }



        seupRecycler()

        val bundle: Bundle? = intent.extras

        bundle?.let {
            val NUm = bundle.getString("address")



            phone.text = NUm
        }



        btnSend.setOnClickListener {

            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.SEND_SMS) !=
                PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this, arrayOf(android.Manifest.permission.SEND_SMS),
                    requestSendSms
                )
            } else {
                SendSms()
            }
        }

        if(ActivityCompat.checkSelfPermission(this,android.Manifest.permission.RECEIVE_SMS) !=
            PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.RECEIVE_SMS),
                requestReceiveSms)
        }
    }

    private fun seupRecycler() {
        mMessageRecycler = this.reyclerview_message_list as RecyclerView
        mMessageAdapter = MessageAdapter(this)
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.VERTICAL
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
                                            grantResults: IntArray) {
        if(requestCode == requestSendSms)SendSms()
    }

    private fun SendSms() {


        val str_address = phone
        val str_message = txtMessage.text.toString()



        SmsManager.getDefault().sendTextMessage(str_address.toString(),null,str_message,null,null)

        Toast.makeText(this,"SMS Sent", Toast.LENGTH_SHORT).show()



    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == SELECT_PICTURE && resultCode == Activity.RESULT_OK){
            try {

                val uri = data!!.data
                imageView2.setImageURI(uri)

            }catch (e : IOException){
                e.printStackTrace()
            }
        }
    }
    fun dispatchGalleryIntent(){
        val intent = Intent(
            Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        //intent.type = "image/*"
        //intent.action = Intent.ACTION_GET_CONTENT
        //startActivityForResult(Intent.createChooser(intent,"SELECT IMAGE"), SELECT_PICTURE)
        startActivityForResult(intent,SELECT_PICTURE)
    }

}

Expected

Convert image into base64 and compress it.

Actual

Nothing happens.


回答1:


If condition because it needs build version 26. Below version it won't work

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
    val bm = BitmapFactory.decodeFile("/path/to/image.jpg")
    val stream = ByteArrayOutputStream()
    bm.compress(CompressFormat.JPEG, 70, stream)
    val byteFormat = stream.toByteArray()
    val imgString = Base64.getEncoder().encodeToString(byteFormat)
}

To Retrieve the Path/to/Image :

val uri = data!!.data
val picturePath = getPath(applicationContext, uri) // Write this line under the uri.
Log.d("Picture Path", picturePath)

This is function to get the path of Image.

private fun getPath(applicationContext: Context, uri: Uri?): String? {
    var result: String? = null
    val proj = arrayOf(MediaStore.Images.Media.DATA)
    val cursor = applicationContext.getContentResolver().query(uri, proj, null, null, null)
    if (cursor != null) {
        if (cursor!!.moveToFirst()) {
            val column_index = cursor!!.getColumnIndexOrThrow(proj[0])
            result = cursor!!.getString(column_index)
        }
        cursor!!.close()
    }
    if (result == null) {
        result = "Not found"
    }
    return result
}



回答2:


In Kotlin, To convert your Image File to Base64 and then compress it

val bm = BitmapFactory.decodeFile("/path/to/image.jpg")
val baos = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos) //bm is the bitmap object
val b = baos.toByteArray()

val encodedImage = Base64.encodeToString(b, Base64.DEFAULT)

You have to replace your image path in the first line.



来源:https://stackoverflow.com/questions/57626536/how-to-convert-an-image-into-base64-and-also-compress-it-using-kotlin-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!