Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...