EDIT: After your clarify, here is what you looking for:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
if (intent.resolveActivity(packageManager) != null) {
startActivityForResult(intent, REQUEST_SELECT_IMAGE_IN_ALBUM)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode === REQUEST_SELECT_IMAGE_IN_ALBUM && resultCode === Activity.RESULT_OK) {
val selectedImage = data?.data
decodeUri(selectedImage!!);
}
}
fun decodeUri(uri: Uri) {
var parcelFD: ParcelFileDescriptor? = null
try {
parcelFD = contentResolver.openFileDescriptor(uri, "r")
val imageSource = parcelFD!!.fileDescriptor
// Decode image size
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
BitmapFactory.decodeFileDescriptor(imageSource, null, o)
// the new size we want to scale to
val REQUIRED_SIZE = 1024
// Find the correct scale value. It should be the power of 2.
var width_tmp = o.outWidth
var height_tmp = o.outHeight
var scale = 1
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
break
}
width_tmp /= 2
height_tmp /= 2
scale *= 2
}
// decode with inSampleSize
val o2 = BitmapFactory.Options()
o2.inSampleSize = scale
val bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2)
imageButton.setImageBitmap(bitmap)
} catch (e: FileNotFoundException) {
// handle errors
} catch (e: IOException) {
// handle errors
} finally {
if (parcelFD != null)
try {
parcelFD.close()
} catch (e: IOException) {
// ignored
}
}
}
I tried myself too.