Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将图像转换为base64并在androidX中使用kotlin对其进行压缩?_Android_Kotlin_Androidx - Fatal编程技术网

如何将图像转换为base64并在androidX中使用kotlin对其进行压缩?

如何将图像转换为base64并在androidX中使用kotlin对其进行压缩?,android,kotlin,androidx,Android,Kotlin,Androidx,我正在创建一个离线短信应用程序。我想知道如何将用户选择的图像转换为字符串base64并对其进行压缩 我搜索了很多资料,但没有找到多少。我找到的所有数据都是Java。但我需要柯特林语 活动文件 class MainActivity1 :AppCompatActivity(){ private val requestReceiveSms: Int = 1 private val requestSendSms: Int = 2 private var mMessageRecy

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

我搜索了很多资料,但没有找到多少。我找到的所有数据都是Java。但我需要柯特林语

活动文件

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

}
class MainActivity1:AppCompatActivity(){
private val requestReceiveSms:Int=1
私有val请求发送SMS:Int=2
私有变量mMessageRecycler:RecyclerView?=null
私有变量mMessageAdapter:MessageAdapter?=null
val选择_图片=5
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn1.setOnClickListener{
调度目录()
}
预循环器()
val bundle:bundle?=intent.extras
捆绑?让我{
val NUm=bundle.getString(“地址”)
phone.text=NUm
}
btnSend.setOnClickListener{
if(ActivityCompat.checkSelfPermission)(这个,android.Manifest.permission.SEND_SMS)=
PackageManager.PERMISSION\u已授予
) {
ActivityCompat.requestPermissions(
这个,arrayOf(android.Manifest.permission.SEND_SMS),
请求发送短信
)
}否则{
SendSms()
}
}
if(ActivityCompat.checkSelfPermission(这个,android.Manifest.permission.RECEIVE_SMS)=
PackageManager.权限(已授予){
ActivityCompat.requestPermissions(这个,arrayOf(android.Manifest.permission.RECEIVE_短信),
requestReceiveSms)
}
}
私家车{
mMessageRecycler=this.reyclerview\u消息\u列表为RecyclerView
mMessageAdapter=MessageAdapter(此)
val layoutManager=LinearLayoutManager(此)
layoutManager.orientation=RecyclerView.VERTICAL
}
重写onRequestPermissionsResult(请求代码:Int,权限:数组,
授予结果:IntArray){
if(requestCode==requestSendSms)SendSms()
}
私人娱乐短信(){
val str_地址=电话
val str_message=txtMessage.text.toString()
SmsManager.getDefault().sendTextMessage(str_address.toString(),null,str_message,null,null)
Toast.makeText(这是“短信发送”,Toast.LENGTH\u SHORT.show())
}
重写activityResult(请求代码:Int,结果代码:Int,数据:Intent?){
super.onActivityResult(请求代码、结果代码、数据)
如果(请求代码==选择图片和结果代码==活动。结果\u确定){
试一试{
val uri=data!!.data
imageView2.setImageURI(uri)
}捕获(e:IOException){
e、 printStackTrace()
}
}
}
娱乐快讯内容(){
val intent=intent(
意向、行动、选择,
MediaStore.Images.Media.EXTERNAL\u CONTENT\u URI)
//intent.type=“image/*”
//intent.action=intent.action\u获取内容
//startActivityForResult(Intent.createChooser(Intent,“选择图像”),选择图片)
startActivityForResult(意图,选择图片)
}
}
预期的

将图像转换为base64并压缩它

实际值


什么也没有发生。

如果条件是因为它需要生成版本26。在下面的版本中,它将不起作用

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)
}
要检索路径/到/图像,请执行以下操作:

val uri = data!!.data
val picturePath = getPath(applicationContext, uri) // Write this line under the uri.
Log.d("Picture Path", picturePath)
这是获取图像路径的函数

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
}

在Kotlin中,将图像文件转换为Base64,然后对其进行压缩

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)

您必须替换第一行中的图像路径。

什么是70…?这是质量。压缩机提示,0-100。0表示小尺寸压缩,100表示最高质量压缩。@A您必须向
位图工厂.decodeFile
提供图像位置,该文件类似于您的uri。我想。
valuri=data!!。data
`imageView2.setImageURI(uri)`我有这两行您想将图像加载到imageview中吗?它已加载..但我想将该图像转换为base64并压缩它基本上是图像路径造成的问题..通过按照@Ashishcan的说明解决了。请检查此。。?