Dưới đây là một ví dụ đầy đủ cho phép yêu cầu (nếu cần), chọn hình ảnh từ thư viện, sau đó chuyển đổi hình ảnh sang bitmap
hoặcfile
AndroidManifesh.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Hoạt động
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button_pick_image.setOnClickListener {
pickImage()
}
}
private fun pickImage() {
if (ActivityCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
val intent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI
)
intent.type = "image/*"
intent.putExtra("crop", "true")
intent.putExtra("scale", true)
intent.putExtra("aspectX", 16)
intent.putExtra("aspectY", 9)
startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE)
} else {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
READ_EXTERNAL_STORAGE_REQUEST_CODE
)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == PICK_IMAGE_REQUEST_CODE) {
if (resultCode != Activity.RESULT_OK) {
return
}
val uri = data?.data
if (uri != null) {
val imageFile = uriToImageFile(uri)
// todo do something with file
}
if (uri != null) {
val imageBitmap = uriToBitmap(uri)
// todo do something with bitmap
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
READ_EXTERNAL_STORAGE_REQUEST_CODE -> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// pick image after request permission success
pickImage()
}
}
}
}
private fun uriToImageFile(uri: Uri): File? {
val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)
val cursor = contentResolver.query(uri, filePathColumn, null, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
val columnIndex = cursor.getColumnIndex(filePathColumn[0])
val filePath = cursor.getString(columnIndex)
cursor.close()
return File(filePath)
}
cursor.close()
}
return null
}
private fun uriToBitmap(uri: Uri): Bitmap {
return MediaStore.Images.Media.getBitmap(this.contentResolver, uri)
}
companion object {
const val PICK_IMAGE_REQUEST_CODE = 1000
const val READ_EXTERNAL_STORAGE_REQUEST_CODE = 1001
}
}
Bản giới thiệu
https://github.com/PhanVanLinh/AndroidPickImage