赞
踩
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)}" } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。