選擇本地圖片是在打開本地文件路徑的時候,通過文件類型進行一次篩選,利用手機本身的內容獲取功能來實現。
一個按鈕動作,根據權限判斷是否需要申請。
//選擇本地圖片
btnChoiceLocalPhoto.setOnClickListener {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf<String>(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1);
} else {
openAlbum();
}
}
//打開相冊
fun openAlbum() {
intent = Intent("android.intent.action.GET_CONTENT")
intent.setType("image/*")
startActivityForResult(intent, CHOOSE_PHOTO)//打開相冊
}
選擇圖片文件之后,返回后
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
CHOOSE_PHOTO -> {
if (resultCode == Activity.RESULT_OK) {
//判斷手機系統版本號
if (Build.VERSION.SDK_INT >= 19) {
//4.4及以上系統使用這個方法處理圖片
handleImageOnKitKat(data)
} else {
//4.4以下系統使用這個方法處理圖片
handeleImageBeforeKitKat(data)
}
}
}
}
}
輔助方法
private fun handleImageOnKitKat(data: Intent) {
// Toast.makeText(this,"到了handleImageOnKitKat(Intent data)方法了", Toast.LENGTH_LONG).show();
var imagePath: String? = null
val uri = data.data
if (DocumentsContract.isDocumentUri(this, uri)) {
//如果是 document 類型的 Uri,則通過 document id 處理
val docId = DocumentsContract.getDocumentId(uri)
if ("com.android.providers.media.documents" == uri!!.authority) {
val id = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1]//解析出數字格式的 id
val selection = MediaStore.Images.Media._ID + "=" + id
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection)
} else if ("com.android.providers.downloads.documents" == uri.authority) {
val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), java.lang.Long.valueOf(docId)!!)
imagePath = getImagePath(contentUri, null)
}
} else if ("content".equals(uri!!.scheme, ignoreCase = true)) {
//如果是 content 類型的 uri , 則使用普通方式處理
imagePath = getImagePath(uri, null)
} else if ("file".equals(uri.scheme, ignoreCase = true)) {
//如果是 file 類型的 Uri,直接獲取圖片路徑即可
imagePath = uri.path
}
displayImage(imagePath)//顯示選中的圖片
}
private fun handeleImageBeforeKitKat(data: Intent) {
val uri = data.data
val imagePath = getImagePath(uri, null)
displayImage(imagePath)
}
private fun getImagePath(uri: Uri?, selection: String?): String? {
var path: String? = null
//通過 Uri 和 selection 來獲取真實的圖片路徑
val cursor = contentResolver.query(uri!!, null, selection, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
}
cursor.close()
}
return path
}
private fun displayImage(imagePath: String?) {
if (imagePath != null) {
val dm = DisplayMetrics() //獲取手機分辨率
windowManager.defaultDisplay.getMetrics(dm)
var options = BitmapFactory.Options() //圖像參數對象,為計算圖像壓縮比使用
options.inJustDecodeBounds = true
var bitmap = BitmapFactory.decodeFile(imagePath, options)
var num = CofoxBitmapInSampleSize(options, dm.widthPixels, dm.heightPixels)
options.inSampleSize = num
options.inJustDecodeBounds = false
nowChooseImagePath = imagePath //保存當前選中圖片的原始路徑
bitmap = BitmapFactory.decodeFile(imagePath, options)//壓縮圖片
imgvwUploadImageSuccess.setImageBitmap(bitmap)
} else {
Toast.makeText(this, "failed to get image", Toast.LENGTH_LONG).show()
}
}