### Install ImagePickerKMP via NPM Source: https://imagepickerkmp.dev/ Use the terminal to install the package for React or JavaScript projects. ```bash npm install imagepickerkmp ``` -------------------------------- ### Compare legacy and modern ImagePickerKMP usage Source: https://imagepickerkmp.dev/ Examples showing the transition from legacy state-based launcher components to the modern, simplified ImagePickerKMP API. ```kotlin var showCamera by remember { mutableStateOf(false) } var photo by remember { mutableStateOf(null) } if (showCamera) { ImagePickerLauncher( config = ImagePickerConfig( onPhotoCaptured = { photo = it showCamera = false }, onError = { showCamera = false }, onDismiss = { showCamera = false } ) ) } Button(onClick = { showCamera = true }) { Text("Camera") } ``` ```kotlin val picker = rememberImagePickerKMP() val imagePickerResponse = picker.result Button(onClick = { picker.launchCamera() }) { Text("Camera") } when(imagePickerResponse) { is ImagePickerResult.Success -> Image(imagePickerResponse.first!!.loadPainter()!!, null) is ImagePickerResponse.Loading -> CircularProgressIndicator() is ImagePickerResult.Error -> Text("Error: ${imagePickerResponse.exception.message}", color = Color.Red) is ImagePickerResult.Dismissed -> Text("Cancelled") Text("Selection cancelled", color = Color.Gray) is ImagePickerResult.Idle -> Text("Press a button to get started", color = Color.Gray) } ``` -------------------------------- ### Install video player dependency Source: https://imagepickerkmp.dev/ Gradle dependency configuration for the upcoming video player module. ```kotlin implementation("io.github.ismoy:imagepickerkmp-video-player:TBD" // coming soon — not yet published) ``` -------------------------------- ### Implement basic video player usage Source: https://imagepickerkmp.dev/ Shows how to initialize the video player with a URL source or programmatic state control. ```kotlin // Simple — just pass a source ImagePickerVideoPlayer( source = VideoSource.Url("https://example.com/video.mp4"), config = VideoPlayerConfig( behavior = VideoBehaviorConfig(autoPlay = true, enablePinchToZoom = true) ) ) // With programmatic control val player = rememberVideoPlayerState(source = VideoSource.Url(videoUrl)) ImagePickerVideoPlayer(state = player, config = VideoPlayerConfig()) Button(onClick = { player.play() }) { Text("Play") } Button(onClick = { player.pause() }) { Text("Pause") } Button(onClick = { player.seekTo(30_000L) }) { Text("Seek 30s") } Button(onClick = { player.toggleFullscreen() }) { Text("Fullscreen") } Button(onClick = { player.enterPiP() }) { Text("PiP") } ``` -------------------------------- ### Implement Custom Audio Player Source: https://imagepickerkmp.dev/ Demonstrates building a custom UI using the low-level audio player state. ```kotlin @Composable fun CustomPlayerScreen(audioUri: String, durationMs: Long) { val playerState = rememberAudioPlayerState( AudioSource.Local( uri = audioUri, durationMs = durationMs, title = "Voice Memo" ) ) val isPlaying = playerState.isPlaying val position = playerState.currentPositionMs val duration = playerState.durationMs val progress = if (duration > 0) position.toFloat() / duration else 0f LinearProgressIndicator(progress = { progress }, modifier = Modifier.fillMaxWidth()) Button(onClick = { if (isPlaying) playerState.pause() else playerState.play() }) { Text(if (isPlaying) "Pause" else "Play") } ``` -------------------------------- ### Basic Camera Implementation Source: https://imagepickerkmp.dev/ Initializes the image picker and handles the result states for camera capture. ```Kotlin val picker = rememberImagePickerKMP() Button(onClick = { picker.launchCamera() }) { Text("Camera") } when (val result = picker.result) { is ImagePickerResult.Success -> { val photo = result.photos.first() } is ImagePickerResult.Error -> { /* handle error */ } is ImagePickerResult.Dismissed -> { /* cancelled */ } else -> {} } ``` -------------------------------- ### Implement Video Picker Source: https://imagepickerkmp.dev/ Configure and use the video picker to record or select videos in Kotlin. ```kotlin val picker = rememberVideoPicker( config = VideoPickerConfig( quality = VideoQuality.FULL_HD_1080P, allowedMimeTypes = listOf(VideoMimeType.MP4), audio = AudioConfig.Default, output = VideoOutputConfig(format = VideoOutputFormat.MP4), validation = VideoValidationConfig( maxDuration = 60.seconds, maxFileSize = 100.mb ) ) ) Button(onClick = { picker.launchCamera() }) { Text("Record") } Button(onClick = { picker.launchGallery() }) { Text("Pick Video") } when (val state = picker.result) { is VideoPickerState.Success -> Text("${state.video.fileName} — ${state.video.durationMs / 1000}s") is VideoPickerState.Error -> Text("Error: ${state.cause}") is VideoPickerState.Cancelled -> Text("Cancelled") else -> {} } ``` -------------------------------- ### Configure Gallery Options Source: https://imagepickerkmp.dev/ Sets up the image picker with specific gallery constraints such as selection limits, EXIF data inclusion, and supported MIME types. ```kotlin val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( galleryConfig = GalleryConfig( allowMultiple = true, selectionLimit = 10, // iOS only — max 10 items includeExif = true, redactGpsData = false, // expose GPS (inform user!) mimeTypes = listOf(MimeType.IMAGE_JPEG, MimeType.IMAGE_PNG) ) ) ) ``` -------------------------------- ### Camera with Compression and Crop Configuration Source: https://imagepickerkmp.dev/ Configures camera capture settings including compression levels, EXIF data handling, and cropping parameters. ```Kotlin val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( cameraCaptureConfig = CameraCaptureConfig( compressionLevel = CompressionLevel.MEDIUM, includeExif = true, redactGpsData = false, cropConfig = CropConfig( enabled = true, circularCrop = true, squareCrop = true, freeformCrop = false ) ) ) ) Button(onClick = { picker.launchCamera() }) { Text("Camera") } when (val result = picker.result) { is ImagePickerResult.Success -> { val photo = result.photos.first() } is ImagePickerResult.Error -> { /* handle error */ } is ImagePickerResult.Dismissed -> { /* cancelled */ } else -> {} } ``` -------------------------------- ### Enable basic crop functionality Source: https://imagepickerkmp.dev/ Minimal configuration to enable the crop UI for camera captures. ```Kotlin val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( cropConfig = CropConfig(enabled = true) ) ) picker.launchCamera() ``` -------------------------------- ### Enable global crop configuration Source: https://imagepickerkmp.dev/ Enables the built-in crop UI globally and demonstrates tracking the crop state using isCropActive. ```Kotlin val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( cropConfig = CropConfig( enabled = true, circularCrop = true, squareCrop = true, freeformCrop = true ) ) ) // isCropActive = true while the crop UI is shown if (picker.isCropActive) { CircularProgressIndicator() } Button(onClick = { picker.launchCamera() }) { Text("Camera + Crop") } Button(onClick = { picker.launchGallery() }) { Text("Gallery + Crop") } ``` -------------------------------- ### launchGallery Source: https://imagepickerkmp.dev/ Opens the gallery interface for file selection. Supports multiple selection and various configuration options. ```APIDOC ## launchGallery(allowMultiple?, mimeTypes?, selectionLimit?, includeExif?, redactGpsData?, mimeTypeMismatchMessage?, cameraCaptureConfig?, onDismiss?, onError?) ### Description Opens the gallery to allow users to select files based on the provided configuration. ### Parameters - **allowMultiple** (Boolean) - Optional - Allow multiple file selection. - **mimeTypes** (List) - Optional - Allowed file types. - **selectionLimit** (Int) - Optional - Maximum selectable files. - **includeExif** (Boolean) - Optional - Extract EXIF metadata. - **redactGpsData** (Boolean) - Optional - Remove GPS data from EXIF. - **mimeTypeMismatchMessage** (String) - Optional - Custom error message for invalid file types. - **cameraCaptureConfig** (CameraCaptureConfig) - Optional - Camera configuration. - **onDismiss** (Function) - Optional - Callback for dismissal. - **onError** (Function) - Optional - Callback for errors. ``` -------------------------------- ### Processing PhotoResult with Built-in Extensions Source: https://imagepickerkmp.dev/ Shows how to use extension functions to load images for UI, convert data to bytes or Base64, and interact with the file system or streams. ```kotlin val picker = rememberImagePickerKMP() when (val result = picker.result) { is ImagePickerResult.Success -> { val photo = result.photos.first() // ── UI & Compose ────────────────────────────────────────────── val painter: Painter? = photo.loadPainter() val bitmap: ImageBitmap? = photo.loadImageBitmap() // ── Data Conversion ────────────────────────────────────────── val bytes: ByteArray = photo.loadBytes() val base64: String = photo.loadBase64() // ── File System & Paths ─────────────────────────────────────── val absPath: String = photo.absolutePath // Direct file path string val path: Path = photo.asPath() // kotlinx.io.files.Path val fileExists: Boolean = photo.exists() // Check if file exists on disk // ── kotlinx-io Streaming ────────────────────────────────────── val source: Source = photo.asSource() // Buffered Source val rawSource: RawSource = photo.asRawSource() // Unbuffered RawSource ``` -------------------------------- ### Seek audio playback with rememberImagePickerKMP Source: https://imagepickerkmp.dev/ Demonstrates how to trigger a seek operation to the beginning of an audio track using a button click. ```kotlin // Seek from a button TextButton(onClick = { playerState.seekTo(0) }) { Text("Restart") } } ``` -------------------------------- ### picker.launchCamera() Source: https://imagepickerkmp.dev/ Triggers the native camera interface for the user to capture an image. ```APIDOC ## picker.launchCamera() ### Description Launches the native camera application. The result of the capture is handled via the `picker.result` state. ### Usage Example ```kotlin Button(onClick = { picker.launchCamera() }) { Text("Camera") } ``` ``` -------------------------------- ### Define Localized PermissionConfig Source: https://imagepickerkmp.dev/ Demonstrates creating a PermissionConfig instance either via localized defaults or by manually specifying strings for dialog titles, descriptions, and buttons. ```kotlin // Create localized PermissionConfig using i18nKonfig strings val config: PermissionConfig = PermissionConfig.createLocalizedComposable() // Custom PermissionConfig val customConfig = PermissionConfig( titleDialogConfig = "Camera Permission", descriptionDialogConfig = "We need camera access to capture photos.", btnDialogConfig = "Open Settings", titleDialogDenied = "Permission Denied", descriptionDialogDenied = "Camera permission is required.", btnDialogDenied = "Grant Permission", btnCancel = "Cancel" ) ``` -------------------------------- ### launchCamera Source: https://imagepickerkmp.dev/ Opens the camera interface. All parameters are optional and override the global configuration for this specific launch. ```APIDOC ## launchCamera(cameraCaptureConfig?, onDismiss?, onError?) ### Description Opens the camera for image capture. Parameters are optional and allow for per-launch configuration overrides. ### Parameters - **cameraCaptureConfig** (CameraCaptureConfig) - Optional - Configuration for camera capture. - **onDismiss** (Function) - Optional - Callback triggered when the camera is dismissed. - **onError** (Function) - Optional - Callback triggered when an error occurs. ``` -------------------------------- ### Implement Basic Scanner Usage Source: https://imagepickerkmp.dev/ Configures the scanner behavior and handles various result states including batch scanning. ```kotlin val scanner = rememberScannerPicker( config = ScannerPickerConfig( camera = ScannerCameraConfig( behavior = ScannerBehaviorConfig( allowedFormats = listOf(BarcodeFormat.QR_CODE, BarcodeFormat.EAN_13), playSound = true ) ) ) ) Button(onClick = { scanner.launchScanner() }) { Text("Scan") } when (val result = scanner.result) { is ScannerPickerState.Success -> Text("${result.result.code} (${result.result.format})") is ScannerPickerState.BatchSuccess -> result.results.forEach { Text(it.code) } is ScannerPickerState.Cancelled -> Text("Cancelled") is ScannerPickerState.Error -> Text("Error: ${result.error}") else -> {} } ``` -------------------------------- ### Add Audio Player Dependency Source: https://imagepickerkmp.dev/ Gradle dependency configuration for the low-level audio player engine. ```kotlin implementation("io.github.ismoy:imagepickerkmp-audio-player:TBD" // coming soon — not yet published) ``` -------------------------------- ### Implement Audio Picker Modal Source: https://imagepickerkmp.dev/ Use the rememberAudioPicker state holder to manage audio recording and file selection. ```kotlin val picker = rememberAudioPicker( config = AudioPickerConfig( validation = AudioPickerValidation( maxFileSizeBytes = 20 * 1024 * 1024L, maxDurationMs = 300_000L ) ), recorderConfig = AudioRecorderConfig(showWaveform = true) ) Button(onClick = { picker.launchRecorder() }) { Text("Record") } Button(onClick = { picker.launchGallery() }) { Text("Pick File") } ``` -------------------------------- ### Launch Gallery with ImagePickerKMP Source: https://imagepickerkmp.dev/ Trigger the gallery picker using the rememberImagePickerKMP composable. ```kotlin Button(onClick = { picker.launchGallery() }) { Text("Gallery") } ``` -------------------------------- ### Override Configuration per Launch Source: https://imagepickerkmp.dev/ Customize gallery or camera settings for a specific invocation without modifying the global configuration. ```Kotlin // JPEG only, max 5 photos, with EXIF for this launch picker.launchGallery( allowMultiple = true, selectionLimit = 5, mimeTypes = listOf(MimeType.IMAGE_JPEG), includeExif = true, redactGpsData = false // GPS included just for this launch ) // Camera with HIGH compression, only for this tap // Crop is controlled via ImagePickerKMPConfig(cropConfig = CropConfig(enabled = true)) picker.launchCamera( cameraCaptureConfig = CameraCaptureConfig( compressionLevel = CompressionLevel.HIGH, includeExif = true ), onDismiss = { /* specific callback on close */ }, onError = { e -> println("Error: ${e.message}") } ) ``` -------------------------------- ### Use AudioRecorder Widget Source: https://imagepickerkmp.dev/ Embed an inline audio recording button directly into your layout. ```kotlin AudioRecorder( config = AudioRecorderConfig( gesture = RecordGesture.HoldAndSlide, showWaveform = true, showDuration = true ), onResult = { audioResult: AudioResult? -> if (audioResult != null) { println("Saved: ${audioResult.uri}, ${audioResult.durationMs}ms") } } ) ``` -------------------------------- ### Configuration Models Source: https://imagepickerkmp.dev/ Configuration objects used to customize the behavior of the ImagePickerKMP library. ```APIDOC ## Configuration Models ### ImagePickerKMPConfig - **cameraCaptureConfig** (CameraCaptureConfig) - **galleryConfig** (GalleryConfig) - **cropConfig** (CropConfig) - **permissionAndConfirmationConfig** (PermissionAndConfirmationConfig) ### CropConfig - **enabled** (Boolean) - Enable crop UI after capture or pick. - **aspectRatioLocked** (Boolean) - Lock aspect ratio. - **circularCrop** (Boolean) - Enable circular crop. - **squareCrop** (Boolean) - Enable square 1:1 crop. - **freeformCrop** (Boolean) - Enable freeform ratio. ``` -------------------------------- ### PermissionAndConfirmationConfig Source: https://imagepickerkmp.dev/ Configuration class for customizing permission handlers, denied dialogs, settings redirection, and iOS alert labels. ```APIDOC ## PermissionAndConfirmationConfig ### Description Configure custom permission handlers, denied dialogs, settings redirection, and iOS alert labels. All properties are optional. ### Properties - **customPermissionHandler** ((PermissionConfig) -> Unit)? - Optional - Custom permission check/request callback receiving localized PermissionConfig - **customDeniedDialog** (@Composable ((onRetry: ()->Unit, onDismiss: ()->Unit) -> Unit)? - Optional - Custom Composable dialog shown when permission is denied - **customSettingsDialog** (@Composable ((onOpenSettings: ()->Unit, onDismiss: ()->Unit) -> Unit)? - Optional - Custom Composable dialog shown when permission is permanently denied - **cancelButtonTextIOS** (String?) - Optional - iOS permission alert cancel button label override - **onCancelPermissionConfigIOS** (() -> Unit)? - Optional - iOS callback executed when user cancels the permission alert ``` -------------------------------- ### PlayerState Methods and Properties Source: https://imagepickerkmp.dev/ Methods and properties available for controlling audio playback state. ```APIDOC ## PlayerState ### Properties - **isPlaying** (Boolean) - Whether audio is currently playing - **currentPositionMs** (Long) - Current playback position in milliseconds - **durationMs** (Long) - Total duration in milliseconds ### Methods - **play()** - Start or resume playback - **pause()** - Pause at current position - **seekTo(positionMs)** - Seek to an arbitrary position ``` -------------------------------- ### Create custom video player layout Source: https://imagepickerkmp.dev/ Uses VideoUIExtensions to define a custom HUD overlay for the video player, including play/pause toggles and position tracking. ```kotlin val config = VideoPlayerConfig( behavior = VideoBehaviorConfig( autoPlay = true, enablePinchToZoom = true, repeatToggleModes = RepeatToggleModes.ONE_AND_ALL ), uiExtensions = VideoUIExtensions( customLayout = { uiState -> val isPlaying = uiState.status == VideoPlayerStatus.Playing Box(modifier = Modifier.fillMaxSize()) { // Custom play/pause button on the right edge Box( modifier = Modifier .size(56.dp) .clip(CircleShape) .background(Color.White.copy(alpha = 0.2f)) .clickable { if (isPlaying) uiState.pause() else uiState.play() } .align(Alignment.CenterEnd), contentAlignment = Alignment.Center ) { Icon( imageVector = if (isPlaying) Icons.Default.Pause else Icons.Default.PlayArrow, tint = Color.White ) } // Position counter Text( text = "${uiState.currentPosition / 1000}s", color = Color.White, modifier = Modifier.align(Alignment.BottomCenter) ) } } ) ) ImagePickerVideoPlayer(source = VideoSource.Url("https://example.com/video.mp4"), config = config) ``` -------------------------------- ### Configure iOS Info.plist permissions Source: https://imagepickerkmp.dev/ Add these keys to your Info.plist to grant the app access to the camera and photo library. ```xml NSCameraUsageDescription Camera access to capture photos NSPhotoLibraryUsageDescription Photo library access to select images NSPhotoLibraryAddUsageDescription Save captured photos to your library NSLocationWhenInUseUsageDescription Location for photo geotagging ``` -------------------------------- ### Configure image compression levels Source: https://imagepickerkmp.dev/ Sets compression levels for camera and gallery captures to manage file size. ```Kotlin // Camera with compression val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( cameraCaptureConfig = CameraCaptureConfig( compressionLevel = CompressionLevel.HIGH ) ) ) picker.launchCamera() // Gallery with compression val galleryPicker = rememberImagePickerKMP( config = ImagePickerKMPConfig( cameraCaptureConfig = CameraCaptureConfig( compressionLevel = CompressionLevel.MEDIUM ) ) ) galleryPicker.launchGallery() ``` -------------------------------- ### Accessing EXIF Metadata with ImagePickerKMP Source: https://imagepickerkmp.dev/ Demonstrates how to access EXIF data from a successful image picker result and configure the gallery picker to include EXIF information. ```kotlin when (val result = picker.result) { is ImagePickerResult.Success -> { result.photos.first().exif?.let { exif -> println("GPS: ${exif.latitude}, ${exif.longitude}") println("Camera: ${exif.cameraModel}") println("Date: ${exif.dateTaken}") println("Flash: ${exif.flash}") println("ISO: ${exif.iso}") println("Shutter: ${exif.shutterSpeed}") println("Size: ${exif.imageWidth} x ${exif.imageHeight} px") } } else -> {} } // Gallery EXIF val galleryPicker = rememberImagePickerKMP( config = ImagePickerKMPConfig( galleryConfig = GalleryConfig(includeExif = true) ) ) galleryPicker.launchGallery() ``` -------------------------------- ### Configure iOS Info.plist for Video Source: https://imagepickerkmp.dev/ Add required privacy keys to the iOS Info.plist file to enable camera, microphone, and photo library access. ```xml NSCameraUsageDescription Required to record video. NSMicrophoneUsageDescription Required to record audio in videos. NSPhotoLibraryUsageDescription Required to select videos from your library. ``` -------------------------------- ### Configure AndroidManifest.xml permissions Source: https://imagepickerkmp.dev/ Android requires no specific permissions for the library, but the camera permission can be added optionally. ```xml ``` -------------------------------- ### Track crop state with UI indicator Source: https://imagepickerkmp.dev/ Displays a loading indicator while the crop UI is active. ```Kotlin if (picker.isCropActive) { CircularProgressIndicator() // crop UI is open } ``` -------------------------------- ### Configure Custom Settings Dialog Source: https://imagepickerkmp.dev/ Defines a custom Composable dialog for scenarios where permissions are permanently denied, allowing users to navigate to system settings. ```kotlin PermissionAndConfirmationConfig( customSettingsDialog = { onOpenSettings, onDismiss -> Dialog(onDismissRequest = onDismiss) { Card(shape = RoundedCornerShape(16.dp)) { Column(modifier = Modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text("Permission Permanently Denied", fontWeight = FontWeight.Bold) Spacer(Modifier.height(12.dp)) Text("Open system settings to enable camera access manually.", color = Color.Gray) Spacer(Modifier.height(20.dp)) Button(onClick = onOpenSettings, modifier = Modifier.fillMaxWidth()) { Text("Open Settings") } } } } } ) ``` -------------------------------- ### rememberImagePickerKMP Source: https://imagepickerkmp.dev/ Initializes the image picker with specific configurations for gallery selection, camera capture, cropping, and compression. ```APIDOC ## rememberImagePickerKMP(config: ImagePickerKMPConfig) ### Description Initializes an image picker instance that allows users to select photos from the gallery or capture them via the camera. The picker state is managed via the returned object, which provides access to the result and launch methods. ### Parameters - **config** (ImagePickerKMPConfig) - Required - Configuration object defining gallery behavior, crop settings, and compression levels. ### Methods - **launchGallery()**: Opens the device photo library for image selection. - **launchCamera()**: Opens the device camera for image capture. ### Result Handling - **picker.result**: Returns an `ImagePickerResult` (Success, Error, or Dismissed). - **picker.isCropActive**: Boolean flag indicating if the crop UI is currently visible. ``` -------------------------------- ### Configure Custom Permission Denied Dialog Source: https://imagepickerkmp.dev/ Uses PermissionAndConfirmationConfig to define a custom Composable dialog for when permissions are denied, providing retry and dismiss callbacks. ```kotlin PermissionAndConfirmationConfig( customDeniedDialog = { onRetry, onDismiss -> Dialog(onDismissRequest = onDismiss) { Card(shape = RoundedCornerShape(16.dp)) { Column(modifier = Modifier.padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally) { Text("Camera Permission Required", fontWeight = FontWeight.Bold) Spacer(Modifier.height(12.dp)) Text("Please grant camera access to take photos.", color = Color.Gray) Spacer(Modifier.height(20.dp)) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { OutlinedButton(onClick = onDismiss, modifier = Modifier.weight(1f)) { Text("Cancel") } Button(onClick = onRetry, modifier = Modifier.weight(1f)) { Text("Retry") } } } } } } ) ``` -------------------------------- ### rememberImagePickerKMP() Source: https://imagepickerkmp.dev/ Initializes the ImagePickerKMP instance to manage camera interactions and capture configurations. ```APIDOC ## rememberImagePickerKMP() ### Description Initializes the image picker component for native camera access. It accepts an optional `ImagePickerKMPConfig` to define capture behavior. ### Parameters - **config** (ImagePickerKMPConfig) - Optional - Configuration object for camera capture, including compression and cropping settings. ### Usage Example ```kotlin val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( cameraCaptureConfig = CameraCaptureConfig( compressionLevel = CompressionLevel.MEDIUM, includeExif = true, redactGpsData = false, cropConfig = CropConfig(enabled = true) ) ) ) ``` ``` -------------------------------- ### Stream photo to sink Source: https://imagepickerkmp.dev/ Streams the selected photo content directly to a file system sink. ```kotlin // Stream directly to a RawSink (file upload / copy) val destinationSink = SystemFileSystem.sink(Path("destination.jpg")) photo.transferToSink(destinationSink) } else -> {} ``` -------------------------------- ### VideoPlayer Control Methods Source: https://imagepickerkmp.dev/ Methods available for programmatic control of the VideoPlayer instance. ```APIDOC ## VideoPlayer Control Methods ### Methods - **play()** - Start playback - **pause()** - Pause playback - **seekTo(positionMs)** - Seek to a specific position in milliseconds - **toggleFullscreen()** - Toggle fullscreen mode - **enterPiP()** - Enter Picture-in-Picture mode ``` -------------------------------- ### PermissionConfig Source: https://imagepickerkmp.dev/ Holds localized titles, descriptions, and button strings for permission dialogs. ```APIDOC ## PermissionConfig ### Description Data class containing localized strings for permission-related dialogs. ### Properties - **titleDialogConfig** (String) - Dialog title - **descriptionDialogConfig** (String) - Dialog description - **btnDialogConfig** (String) - Dialog button text - **titleDialogDenied** (String) - Denied dialog title - **descriptionDialogDenied** (String) - Denied dialog description - **btnDialogDenied** (String) - Denied dialog button text - **btnCancel** (String) - Cancel button text ``` -------------------------------- ### rememberImagePickerKMP Source: https://imagepickerkmp.dev/ The primary entry point for the ImagePickerKMP library. It returns a state object used to launch the camera or gallery and monitor the picker result. ```APIDOC ## rememberImagePickerKMP ### Description Provides a reactive state for managing image picking operations including camera capture and gallery selection. ### Methods - **launchCamera(cameraCaptureConfig?, onDismiss?, onError?)**: Opens the camera interface. Parameters override global configuration. - **launchGallery(allowMultiple?, mimeTypes?, selectionLimit?, includeExif?, redactGpsData?, mimeTypeMismatchMessage?, cameraCaptureConfig?, onDismiss?, onError?)**: Opens the gallery interface. Parameters override global configuration. - **reset()**: Resets the picker state to Idle and clears active UI states. ### Properties - **result** (ImagePickerResult) - Reactive state: Idle, Loading, Success, Dismissed, or Error. - **isCropActive** (Boolean) - Indicates if the crop UI is currently visible. ``` -------------------------------- ### rememberImagePickerKMP Source: https://imagepickerkmp.dev/ Initializes the image picker with specific configuration, such as enabling EXIF data retrieval. ```APIDOC ## rememberImagePickerKMP ### Description Initializes the image picker instance. Use the `config` parameter to enable features like EXIF data collection. ### Parameters - **config** (ImagePickerKMPConfig) - Optional - Configuration object including `GalleryConfig` or `CameraCaptureConfig`. ### Example ```kotlin val galleryPicker = rememberImagePickerKMP( config = ImagePickerKMPConfig( galleryConfig = GalleryConfig(includeExif = true) ) ) galleryPicker.launchGallery() ``` -------------------------------- ### Select multiple photos with MIME filtering Source: https://imagepickerkmp.dev/ Configures the picker to allow multiple selections with a limit and specific MIME type filters. ```Kotlin val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( galleryConfig = GalleryConfig( allowMultiple = true, selectionLimit = 10, mimeTypes = listOf( MimeType.IMAGE_JPEG, MimeType.IMAGE_PNG, MimeType.IMAGE_WEBP ) ) ) ) Button(onClick = { picker.launchGallery() }) { Text("Gallery") } when (val result = picker.result) { is ImagePickerResult.Success -> { result.photos.forEach { /* use photo */ } } is ImagePickerResult.Error -> { /* handle error */ } is ImagePickerResult.Dismissed -> { /* cancelled */ } else -> {} } ``` -------------------------------- ### rememberImagePickerKMP() Source: https://imagepickerkmp.dev/ The primary entry point for initializing the image picker state in a Composable. It accepts an optional ImagePickerKMPConfig to define global behavior for camera and gallery operations. ```APIDOC ## rememberImagePickerKMP(config: ImagePickerKMPConfig) ### Description Initializes the image picker state holder. This is the recommended entry point for all new code using the library. ### Parameters - **config** (ImagePickerKMPConfig) - Optional - Global configuration for camera, gallery, crop, and permission settings. ### Returns - **ImagePickerKMPState** - A stable state holder that exposes the current result and provides methods to launch the camera or gallery. ``` -------------------------------- ### Implement ImagePickerKMP in a Composable Source: https://imagepickerkmp.dev/ Use rememberImagePickerKMP to initialize the picker and handle reactive states for loading, success, error, and idle scenarios. ```Kotlin @Composable fun MyScreen(innerPadding: PaddingValues) { // 1. Create the picker with a global config val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( enableCrop = false, galleryConfig = GalleryConfig( allowMultiple = true, selectionLimit = 10, includeExif = true, redactGpsData = true, mimeTypes = listOf(MimeType.IMAGE_JPEG) ) ) ) // 2. Read the reactive result val result = picker.result Column( modifier = Modifier .padding(innerPadding) .fillMaxSize() ) { // 3. React to each picker state Box( modifier = Modifier.fillMaxWidth().weight(1f), contentAlignment = Alignment.Center ) { when (result) { is ImagePickerResult.Loading -> { Column(horizontalAlignment = Alignment.CenterHorizontally) { CircularProgressIndicator() Text("Selecting...", color = Color.Gray) } } is ImagePickerResult.Success -> { val photos = result.photos if (photos.size == 1) { // Single photo (camera or simple gallery) val painter = photos.first().loadPainter() if (painter != null) { Image(painter = painter, contentDescription = "Captured photo") } } else { // Multiple gallery photos LazyVerticalGrid(columns = GridCells.Fixed(2)) { items(photos) { photo -> val painter = photo.loadPainter() if (painter != null) { Image(painter = painter, contentDescription = null) } } } } } is ImagePickerResult.Error -> Text("Error: ${result.exception.message}", color = Color.Red) is ImagePickerResult.Dismissed, is ImagePickerResult.Idle -> Text("No image selected", color = Color.Gray) } } // 4. Buttons that trigger the picker directly Row(modifier = Modifier.fillMaxWidth().padding(16.dp)) { Button( onClick = { picker.launchCamera() }, modifier = Modifier.weight(1f) ) { Text("Camera") } Button( onClick = { picker.launchGallery() }, modifier = Modifier.weight(1f) ) { Text("Gallery") } } } } ``` -------------------------------- ### GalleryConfig Source: https://imagepickerkmp.dev/ Configuration options for gallery image selection. ```APIDOC ## GalleryConfig ### Description Defines behavior for gallery image selection, including multi-selection and metadata handling. ### Properties - **allowMultiple** (Boolean) - Enable multiple image selection - **selectionLimit** (Int) - Max items to select (iOS only) - **includeExif** (Boolean) - Include EXIF metadata - **redactGpsData** (Boolean) - Redact GPS data from metadata - **mimeTypes** (List) - List of allowed MIME types ``` -------------------------------- ### Add Audio Picker Dependency Source: https://imagepickerkmp.dev/ Include the audio picker module in your Gradle build file. ```kotlin implementation("io.github.ismoy:imagepickerkmp-audio:TBD" // coming soon — not yet published) ``` -------------------------------- ### Add Video Picker Dependency Source: https://imagepickerkmp.dev/ Include the video picker module in your Gradle build file. ```kotlin implementation("io.github.ismoy:imagepickerkmp-video:TBD" // coming soon — not yet published) ``` -------------------------------- ### MimeType Configuration Source: https://imagepickerkmp.dev/ Utility methods and enum values for filtering file types in the image picker. ```APIDOC ## MimeType Utility ### Description Use MimeType enum values to filter selectable files in GalleryConfig and utilize utility methods for conversion. ### Utility Methods - **MimeType.toMimeTypeStrings(vararg types)** (List) - Converts MimeType enum values to a list of MIME strings. - **MimeType.fromString(string)** (MimeType) - Parses a MIME string into a MimeType enum value. ### Supported MimeTypes - IMAGE_ALL (image/*) - IMAGE_JPEG (image/jpeg) - IMAGE_PNG (image/png) - IMAGE_WEBP (image/webp) - IMAGE_GIF (image/gif) - IMAGE_BMP (image/bmp) - IMAGE_HEIC (image/heic) - IMAGE_HEIF (image/heif) - APPLICATION_PDF (application/pdf) ``` -------------------------------- ### Add ImagePickerKMP dependency to build.gradle.kts Source: https://imagepickerkmp.dev/ Include the library in your commonMain dependencies for Kotlin Multiplatform projects. ```kotlin // commonMain dependencies — add only what your app uses // ✅ Published on Maven Central implementation("io.github.ismoy:imagepickerkmp:1.1.0") // Photo // 🔜 Coming soon — not yet published // implementation("io.github.ismoy:imagepickerkmp-video:??") // implementation("io.github.ismoy:imagepickerkmp-audio:??") // implementation("io.github.ismoy:imagepickerkmp-audio-player:??") // implementation("io.github.ismoy:imagepickerkmp-scanner:??") // implementation("io.github.ismoy:imagepickerkmp-video-player:??") ``` -------------------------------- ### useImagePicker (Web/JS) Source: https://imagepickerkmp.dev/ The useImagePicker hook allows web applications to trigger camera or gallery selection and handle the resulting media files. ```APIDOC ## useImagePicker ### Description A React hook for web applications to open the camera or gallery and handle media selection results. ### Parameters - **onPhotoCaptured** (function) - Callback triggered when a photo is successfully captured or selected. - **onError** (function) - Callback triggered when an error occurs during the selection process. ### Returns - **openCamera** (function) - Function to trigger the camera interface. - **openGallery** (function) - Function to trigger the gallery interface. - **result** (object) - The captured media result containing uri, fileName, and fileSize. ``` -------------------------------- ### Extract EXIF metadata Source: https://imagepickerkmp.dev/ Enables EXIF metadata extraction by setting includeExif to true in the camera configuration. ```Kotlin val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( cameraCaptureConfig = CameraCaptureConfig(includeExif = true) ) ) picker.launchCamera() ``` -------------------------------- ### Handle ImagePickerKMP state exhaustively Source: https://imagepickerkmp.dev/ Use a when expression to handle the various states of the ImagePickerResult, including loading, success, and error states. ```kotlin when (val result = picker.result) { is ImagePickerResult.Idle -> Text("No image selected", color = Color.Gray) is ImagePickerResult.Loading -> CircularProgressIndicator() is ImagePickerResult.Success -> { // result.photos: List // result.first: PhotoResult? (first photo, useful for camera) result.photos.forEach { photo -> val painter = photo.loadPainter() // Painter for Compose val bytes = photo.loadBytes() // ByteArray for file operations val bitmap = photo.loadImageBitmap() // ImageBitmap for graphics val base64 = photo.loadBase64() // Base64 for APIs } } is ImagePickerResult.Dismissed -> Text("Cancelled by user") is ImagePickerResult.Error -> Text("Error: ${result.exception.message}", color = Color.Red) } ``` -------------------------------- ### Select single photo with ImagePickerKMP Source: https://imagepickerkmp.dev/ Configures the picker for single selection mode and handles the result state. ```Kotlin val picker = rememberImagePickerKMP( config = ImagePickerKMPConfig( galleryConfig = GalleryConfig(allowMultiple = false) ) ) Button(onClick = { picker.launchGallery() }) { Text("Gallery") } when (val result = picker.result) { is ImagePickerResult.Success -> { val photo = result.photos.first() } is ImagePickerResult.Error -> { /* handle error */ } is ImagePickerResult.Dismissed -> { /* cancelled */ } else -> {} } ``` -------------------------------- ### Handle Audio Picker State Source: https://imagepickerkmp.dev/ Processes the result of an audio picker operation to display metadata or play audio using a specific layout. ```kotlin when (val state = picker.result) { is AudioPickerState.Success -> { val audio = state.audio Text("${audio.fileName} — ${audio.durationMs / 1000}s") ImagePickerAudioPlayer( state = rememberAudioPlayerState( AudioSource.Local( uri = audio.uri, durationMs = audio.durationMs, title = audio.fileName ) ), layout = AudioPlayerLayout.VoiceMessage() ) } is AudioPickerState.Error -> Text("Error: ${state.cause}") is AudioPickerState.Cancelled -> Text("Cancelled") else -> {} } ``` -------------------------------- ### Add Scanner Dependency Source: https://imagepickerkmp.dev/ Gradle dependency configuration for the upcoming scanner module. ```kotlin implementation("io.github.ismoy:imagepickerkmp-scanner:TBD" // coming soon — not yet published) ``` -------------------------------- ### Manage MimeType conversions Source: https://imagepickerkmp.dev/ Utility methods for converting MimeType enums to strings and parsing strings back to MimeType enums. ```kotlin // Convert to string list val strings = MimeType.toMimeTypeStrings( MimeType.IMAGE_JPEG, MimeType.IMAGE_PNG ) // → ["image/jpeg", "image/png"] // Parse from string val mt = MimeType.fromString("image/webp") // → MimeType.IMAGE_WEBP ``` -------------------------------- ### rememberImagePickerKMP (Kotlin Multiplatform) Source: https://imagepickerkmp.dev/ A composable function for Kotlin Multiplatform projects to configure and launch image selection. ```APIDOC ## rememberImagePickerKMP ### Description Configures and provides an image picker instance for KMP applications. ### Parameters - **allowMultiple** (Boolean) - Optional - Enable multi-file selection. Default: false. - **mimeTypes** (List) - Optional - Allowed file types. Default: [IMAGE_ALL]. - **selectionLimit** (Int) - Optional - Max items when allowMultiple is enabled (iOS). Default: 30. - **includeExif** (Boolean) - Optional - Extract EXIF metadata. Default: false. - **redactGpsData** (Boolean) - Optional - Strip GPS from EXIF. Default: true. ``` -------------------------------- ### ImagePickerKMPState Methods Source: https://imagepickerkmp.dev/ Methods available on the state object returned by rememberImagePickerKMP() to trigger image selection. ```APIDOC ## launchCamera(cameraCaptureConfig: CameraCaptureConfig?, onDismiss: () -> Unit, onError: (Exception) -> Unit) ### Description Triggers the camera capture flow. ### Parameters - **cameraCaptureConfig** (CameraCaptureConfig) - Optional - Per-launch override for camera settings. - **onDismiss** (() -> Unit) - Optional - Callback invoked when the picker is closed. - **onError** ((Exception) -> Unit) - Optional - Callback invoked when an error occurs. ## launchGallery(allowMultiple: Boolean, selectionLimit: Int, mimeTypes: List, includeExif: Boolean, redactGpsData: Boolean) ### Description Triggers the gallery selection flow with optional per-launch overrides. ### Parameters - **allowMultiple** (Boolean) - Optional - Whether to allow selecting multiple images. - **selectionLimit** (Int) - Optional - Maximum number of images to select. - **mimeTypes** (List) - Optional - List of allowed MIME types. - **includeExif** (Boolean) - Optional - Whether to include EXIF data. - **redactGpsData** (Boolean) - Optional - Whether to redact GPS data from selected images. ``` -------------------------------- ### reset Source: https://imagepickerkmp.dev/ Resets the picker state to Idle and clears any active UI. ```APIDOC ## reset() ### Description Resets the result state to Idle, clears isCropActive, and closes any active picker. ``` -------------------------------- ### Photo Processing Methods Source: https://imagepickerkmp.dev/ Methods available on the photo object to load, convert, or stream image data. ```APIDOC ## Photo Processing Methods ### Description These methods allow you to process the selected photo, including decoding into Compose types, reading as bytes, or streaming to a sink. ### Methods - **photo.loadPainter()** (Painter?) - Decodes image into Compose Painter for Image() composables. - **photo.loadImageBitmap()** (ImageBitmap?) - Decodes image into Compose ImageBitmap for Canvas rendering. - **photo.loadBytes()** (ByteArray) - Reads complete file content into a byte array. - **photo.loadBase64()** (String) - Encodes image data to Base64 string for REST API payloads. - **photo.absolutePath** (String) - Returns direct platform file path. - **photo.asPath()** (Path) - Converts absolutePath into a kotlinx.io.files.Path. - **photo.exists()** (Boolean) - Verifies if the file exists on the local file system. - **photo.asSource()** (Source) - Opens a buffered kotlinx.io.Source for high-performance reading. - **photo.asRawSource()** (RawSource) - Opens an unbuffered kotlinx.io.RawSource for low-level file reading. - **photo.transferToSink(sink)** (Unit) - Streams the photo content directly into any kotlinx.io.RawSink. ``` -------------------------------- ### Use ImagePicker in React Source: https://imagepickerkmp.dev/ Integrate the image picker into a React component using the useImagePicker hook. ```typescript import { useImagePicker } from 'imagepickerkmp'; function PhotoUploader() { const { openCamera, openGallery, result } = useImagePicker({ onPhotoCaptured: (photo) => { console.log('Photo:', photo.fileName, photo.fileSize); }, onError: (err) => console.error(err) }); return (
{result && captured}
); } ``` -------------------------------- ### PhotoResult Source: https://imagepickerkmp.dev/ The result object returned after a successful image capture or selection. ```APIDOC ## PhotoResult ### Fields - **uri** (String) - Platform-native URI. - **fileName** (String?) - File name. - **fileSize** (Long?) - Size in bytes. - **mimeType** (String?) - MIME type. - **width** (Int?) - Width in pixels. - **height** (Int?) - Height in pixels. - **exif** (ExifData?) - Metadata if enabled. ### Extension Methods - **asPath()**: Returns kotlinx.io.files.Path. - **exists()**: Checks file existence. - **loadBytes()**: Reads file into ByteArray. - **loadBase64()**: Encodes to Base64. - **loadPainter()**: Decodes to Compose Painter. - **loadImageBitmap()**: Decodes to Compose ImageBitmap. ``` -------------------------------- ### PhotoResult Extensions Source: https://imagepickerkmp.dev/ Methods available on photo result objects to load data, render images, or access file system paths. ```APIDOC ## PhotoResult Extensions ### Description Extensions provided on `PhotoResult` objects to facilitate UI rendering, data conversion, and file system interaction. ### Methods - **loadPainter()**: Returns a `Painter?` for Compose UI. - **loadImageBitmap()**: Returns an `ImageBitmap?`. - **loadBytes()**: Returns `ByteArray` of the image. - **loadBase64()**: Returns `String` representation of the image. - **absolutePath**: `String` property for the file path. - **asPath()**: Returns `kotlinx.io.files.Path`. - **exists()**: `Boolean` check for file existence. - **asSource()**: Returns `Source` (Buffered). - **asRawSource()**: Returns `RawSource` (Unbuffered). ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.