安卓如何从相册获取图片到imageview中 使用kotlin编写 并保证在Android 10可用
时间: 2023-05-29 18:06:47 浏览: 314
以下是使用kotlin编写的安卓代码,用于从相册中选择图片并将其显示在ImageView中。
首先,需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
然后,在Activity的onCreate方法中添加以下代码:
```kotlin
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 1)
```
这将打开系统的相册应用程序,让用户选择一个图片。
在Activity中添加以下方法,以处理用户选择的图片:
```kotlin
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
val imageUri = data.data
if (imageUri != null) {
val bitmap = getBitmapFromUri(imageUri)
imageView.setImageBitmap(bitmap)
}
}
}
private fun getBitmapFromUri(uri: Uri): Bitmap? {
val inputStream = contentResolver.openInputStream(uri)
return BitmapFactory.decodeStream(inputStream)
}
```
此代码首先检查requestCode和resultCode是否与我们启动Activity时使用的值匹配。如果匹配,则获取用户选择的图片的URI。
然后,我们调用getBitmapFromUri方法,该方法从URI获取输入流,并使用BitmapFactory将其解码为Bitmap对象。最后,我们将该位图设置到ImageView中。
请注意,这种方法可能无法在Android 10中正常工作,因为Android 10中引入了一些更严格的文件访问权限。要在Android 10中使用此方法,请确保在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
并使用以下代码打开图库:
```kotlin
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.type = "image/*"
startActivityForResult(intent, 1)
```
这将打开系统的文档应用程序,让用户选择一个图片。在处理用户选择的图片时,您需要使用以下方法获取输入流:
```kotlin
private fun getBitmapFromUri(uri: Uri): Bitmap? {
val inputStream = contentResolver.openInputStream(uri)
return BitmapFactory.decodeStream(inputStream)
}
```
请注意,Android 10中,您需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
并在应用程序运行时请求这些权限。
以上是使用kotlin编写的安卓代码,用于从相册中选择图片并将其显示在ImageView中,并保证在Android 10中可用。