-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathImagePickerBS
364 lines (354 loc) · 15.4 KB
/
ImagePickerBS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Camera
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ImageSearch
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.content.FileProvider
import coil.compose.AsyncImage
import your.package.BuildConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
/**
* ImagePickerBs is a composable that allows you to pick an image from the gallery or take a photo,
* it displays a modal bottom sheet with two buttons, one for the gallery and the other for the camera,
* it also allows you to choose from recent wallpapers if the folder exists and is not empty,
* this also resizes the image to a maximum width and height without loosing original aspect ratio if skipResize is false
* i.e it will resize the image to fit within the maximum width and height
* image width may not be equal to max width and max height
*
* Note: this composable uses Coil to load images from the file system
*
* @param showImagesFromParent if true, it will show images from the parent folder
* @param allowDelete if true, it will allow you to delete images from the parent folder
* @param file the file where the image will be saved
* @param skipResize if true, it will not resize the image, may cause out of memory error
* @param maxBitmapWidth the maximum width of the bitmap
* @param maxBitmapHeight the maximum height of the bitmap
* @param onDismissRequest a lambda that will be called when the modal bottom sheet is dismissed
* @param onImagePicked a lambda that will be called when an image is picked
* @param onShowProgress a lambda that will be called when the image is being processed
* @param modifier the modifier for the modal bottom sheet
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImagePickerBs(
modifier: Modifier = Modifier,
file: File, ///file used to save image for future use
maxBitmapWidth: Int = 1024,
maxBitmapHeight: Int = 1024,
skipResize: Boolean = false,
onDismissRequest: () -> Unit,
onImagePicked: (File) -> Unit,
onShowProgress: (Boolean) -> Unit = {},
showImagesFromParent: Boolean = true,
allowDelete: Boolean = true
) {
val scope = rememberCoroutineScope()
val folder = file.parentFile
val context = LocalContext.current
val imagePicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia(),
onResult = { uri ->
if (folder != null)
try {
if (folder.exists() || folder.mkdirs()) {
if (!file.exists() || file.delete()) {
file.createNewFile()
}
}
if (uri != null) {
val bitmap = uri.getBitmap(context)
if (bitmap.width > maxBitmapWidth || bitmap.height > maxBitmapHeight || !skipResize) {
scope.launch {
withContext(Dispatchers.IO) {
if (bitmap.width > bitmap.height) {
val ratio = bitmap.width.toFloat() / bitmap.height.toFloat()
val newHeight = (maxBitmapWidth / ratio).toInt()
val newBitmap =
Bitmap.createScaledBitmap(
bitmap,
maxBitmapWidth,
newHeight,
true
)
newBitmap.saveToFile(file)
} else {
val ratio = bitmap.height.toFloat() / bitmap.width.toFloat()
val newWidth = (maxBitmapHeight / ratio).toInt()
val newBitmap =
Bitmap.createScaledBitmap(
bitmap,
newWidth,
maxBitmapHeight,
true
)
newBitmap.saveToFile(file)
}
onImagePicked(file)
}
}
} else if (uri.copyToFile(file, context)) {
onImagePicked(file)
}
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
onShowProgress(false)
}
}
)
val cameraPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.TakePicture(),
onResult = { success ->
try {
if (success) {
val bitmap = BitmapFactory.decodeFile(file.absolutePath)
if (bitmap.width > maxBitmapWidth || bitmap.height > maxBitmapHeight || !skipResize) {
scope.launch {
withContext(Dispatchers.IO) {
if (bitmap.width > bitmap.height) {
val ratio = bitmap.width.toFloat() / bitmap.height.toFloat()
val newHeight = (maxBitmapWidth / ratio).toInt()
val newBitmap =
Bitmap.createScaledBitmap(
bitmap,
maxBitmapWidth,
newHeight,
true
)
newBitmap.saveToFile(file)
} else {
val ratio = bitmap.height.toFloat() / bitmap.width.toFloat()
val newWidth = (maxBitmapHeight / ratio).toInt()
val newBitmap =
Bitmap.createScaledBitmap(
bitmap,
newWidth,
maxBitmapHeight,
true
)
newBitmap.saveToFile(file)
}
onImagePicked(file)
}
}
} else {
onImagePicked(file)
}
}
} catch (e: Exception) {
e.printStackTrace()
} finally {
onShowProgress(false)
}
}
)
ModalBottomSheet(
onDismissRequest = {
onDismissRequest()
},
modifier = modifier
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(5.dp)
) {
Text(
"Choose an Image",
modifier = Modifier
.padding(10.dp)
.fillMaxWidth(),
style = MaterialTheme.typography.titleLarge,
color = Color.Black,
textAlign = TextAlign.Center
)
Text(
"from the gallery or take a photo",
modifier = Modifier
.padding(10.dp)
.fillMaxWidth(),
style = MaterialTheme.typography.bodyMedium,
color = Color.Black,
textAlign = TextAlign.Center
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
Button(
onClick = {
onShowProgress(true)
if (folder != null) {
if (folder.exists() || folder.mkdirs()) {
if (!file.exists() || file.delete()) {
file.createNewFile()
}
}
val fileUri = FileProvider.getUriForFile(
context,
BuildConfig.APPLICATION_ID + ".provider",
file
)
cameraPicker.launch(fileUri)
}
},
modifier = Modifier.padding(10.dp)
) {
Icon(Icons.Filled.Camera, contentDescription = "Camera")
Text("Camera", modifier = Modifier.padding(horizontal = 4.dp))
}
Button(
onClick = {
onShowProgress(true)
imagePicker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
},
modifier = Modifier.padding(10.dp)
) {
Icon(Icons.Filled.ImageSearch, contentDescription = "Gallery")
Text("Gallery", modifier = Modifier.padding(horizontal = 4.dp))
}
}
if (folder != null && showImagesFromParent) {
if (folder.exists() && folder.listFiles()?.isNotEmpty() == true) {
Text(
"Or choose from Recent Wallpapers",
modifier = Modifier
.padding(10.dp)
.fillMaxWidth(),
style = MaterialTheme.typography.bodyMedium,
color = Color.Black,
textAlign = TextAlign.Center
)
val filesList = folder.listFiles()!!.toMutableList()
LazyRow {
items(folder.listFiles()!!.toList()) {
Box(
modifier = Modifier
.width(100.dp)
.height(100.dp)
.padding(5.dp)
.clip(RoundedCornerShape(10.dp))
.background(Color.Gray)
) {
AsyncImage(
model = it,
contentDescription = "Wallpaper",
modifier = Modifier
.fillMaxSize()
.clickable {
onImagePicked(it)
},
contentScale = ContentScale.Crop
)
if (allowDelete)
Icon(
imageVector = Icons.Filled.Close,
contentDescription = "Remove",
modifier = Modifier
.align(Alignment.TopEnd)
.size(20.dp)
.padding(2.dp)
.background(Color.White, shape = CircleShape)
.clip(CircleShape)
.padding(2.dp)
.clickable {
it.delete()
filesList.remove(it)
}
)
}
}
}
}
}
}
}
}
///Save a bitmap into file
fun Bitmap.saveToFile(
file: File,
format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG,
quality: Int = 85
): Boolean {
return try {
FileOutputStream(file).use { out ->
this.compress(format, quality, out)
}
true
} catch (e: IOException) {
e.printStackTrace()
false
}
}
@Suppress("DEPRECATION")
fun Uri.getBitmap(context: Context): Bitmap {
return if (Build.VERSION.SDK_INT < 28) {
MediaStore.Images.Media.getBitmap(
context.contentResolver,
this
)
} else {
val source = ImageDecoder.createSource(context.contentResolver, this)
ImageDecoder.decodeBitmap(source)
}
}
///Copy content of an uri to another file
fun Uri.copyToFile(file: File, context: Context): Boolean {
return try {
context.contentResolver.openInputStream(this).use { input ->
file.outputStream().use { output ->
input?.copyTo(output)
}
}
true
} catch (e: Exception) {
e.printStackTrace()
false
}
}