Skip to content

Commit fa52405

Browse files
add image selection button
1 parent 564152f commit fa52405

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.smarttoolfactory.composeimage
2+
3+
import android.annotation.SuppressLint
4+
import android.graphics.Bitmap
5+
import android.graphics.ImageDecoder
6+
import android.os.Build
7+
import android.provider.MediaStore
8+
import androidx.activity.compose.rememberLauncherForActivityResult
9+
import androidx.compose.material.icons.Icons
10+
import androidx.compose.material.icons.filled.Add
11+
import androidx.compose.material3.FloatingActionButton
12+
import androidx.compose.material3.FloatingActionButtonDefaults
13+
import androidx.compose.material3.FloatingActionButtonElevation
14+
import androidx.compose.material3.Icon
15+
import androidx.compose.runtime.Composable
16+
import androidx.compose.ui.graphics.ImageBitmap
17+
import androidx.compose.ui.graphics.asImageBitmap
18+
import androidx.compose.ui.platform.LocalContext
19+
import com.google.modernstorage.photopicker.PhotoPicker
20+
21+
@SuppressLint("UnsafeOptInUsageError")
22+
@Composable
23+
fun ImageSelectionButton(
24+
elevation: FloatingActionButtonElevation = FloatingActionButtonDefaults.elevation(),
25+
onImageSelected: (ImageBitmap) -> Unit
26+
) {
27+
val context = LocalContext.current
28+
29+
val photoPicker =
30+
rememberLauncherForActivityResult(PhotoPicker()) { uris ->
31+
val uri = uris.firstOrNull() ?: return@rememberLauncherForActivityResult
32+
33+
val bitmap: Bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
34+
ImageDecoder.decodeBitmap(
35+
ImageDecoder.createSource(context.contentResolver, uri)
36+
) { decoder, info, source ->
37+
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
38+
decoder.isMutableRequired = true
39+
}
40+
} else {
41+
MediaStore.Images.Media.getBitmap(context.contentResolver, uri)
42+
}
43+
44+
onImageSelected(bitmap.asImageBitmap())
45+
46+
}
47+
48+
FloatingActionButton(
49+
elevation = elevation,
50+
onClick = {
51+
photoPicker.launch(PhotoPicker.Args(PhotoPicker.Type.IMAGES_ONLY, 1))
52+
},
53+
) {
54+
Icon(
55+
imageVector = Icons.Default.Add,
56+
contentDescription = null
57+
)
58+
}
59+
}

0 commit comments

Comments
 (0)