如何在androidX中将图像转换为base64并使用kotlin对其进行压缩? [英] How to convert an image into base64 and also compress it using kotlin in androidX?

查看:833
本文介绍了如何在androidX中将图像转换为base64并使用kotlin对其进行压缩?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个离线SMS应用程序.我想知道如何将用户选择的图像转换为字符串base64并对其进行压缩.

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.

我搜索了很多东西,但没有找到太多材料,我发现的所有数据都在Java中.但是我需要用科特林语言.

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.

活动文件

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)
    }

}

期望

将图像转换为base64并进行压缩.

Convert image into base64 and compress it.

实际

什么都没发生.

推荐答案

如果由于需要版本26而出现问题.低于该版本将无法正常工作

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
}

这篇关于如何在androidX中将图像转换为base64并使用kotlin对其进行压缩?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆