当前位置:   article > 正文

Kotlin Uri 处理工具类

kotlin uri

Kotlin Uri 处理工具类

import android.net.Uri
import android.provider.MediaStore
import android.util.Base64
import androidx.loader.content.CursorLoader
import com.purui.mobile.PuruiApplication


object UriUtils {

    private fun uriToPath(uri:Uri?):String {
        if (uri == null) return ""
        //encode the image
        return try {
            //get the image path
            val projection = arrayOf(MediaStore.Images.Media.DATA)
            val cursorLoader = CursorLoader(PuruiApplication.instance, uri, projection, null, null, null)
            val cursor = cursorLoader.loadInBackground()
            val column_index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)?:0
            cursor?.moveToFirst()
            val path = cursor?.getString(column_index)
            path?:""
        } catch (ex: Exception) {
            ""
        }
    }

    private fun uriToBase64(uri:Uri?) :String {
        if (uri == null) return ""
        return try {
            var result = ""
            PuruiApplication.instance.contentResolver?.openInputStream(uri)?.let {
                result = Base64.encodeToString(it.readBytes(),Base64.DEFAULT)
            }
            result
        } catch (ex: java.lang.Exception) {
            ""
        }
    }

    fun uriToFullBase64(uri: Uri?):String {
        val path = uriToPath(uri)
        val prefix = if (path.endsWith("png")) "data:image/png;base64," else "data:image/jpeg;base64,"
        return "$prefix${uriToBase64(uri)}"
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号