By Shakil Ahmed, Android developer & software engineer
Read Text from Photos in Android with ML Kit and Jetpack Compose
Pick a photo, read its text on-device with ML Kit Text Recognition v2, and show blocks and lines in Jetpack Compose with a copy button.
Have you ever typed text from a photo into your phone, letter by letter? With ML Kit text recognition, your Android app can read that text for you in less than a second. In this tutorial, we will build a small app that picks a photo, reads the text inside it, and lets the user copy it with one tap.
Everything runs on the device. No server, no API key, no internet needed for the bundled model. That makes it a great first "AI feature" for beginners.
Here is what we will build:
- Pick an image with the Android Photo Picker
- Run ML Kit Text Recognition v2 on it
- Show the full text, plus each block and line
- A Copy button
- Loading and error states handled in a ViewModel with coroutines
If you are new to ViewModels or coroutines, read Jetpack Compose ViewModel for Beginners and Kotlin Coroutines Guide first. They will make this post much easier.
What Is ML Kit Text Recognition?
ML Kit is Google's mobile machine learning SDK. Its Text Recognition v2 API looks at an image and returns the text it finds, organized like this:
| Level | Class | What it means |
|---|---|---|
| Whole result | Text | All recognized text in the image |
| Block | TextBlock | A paragraph or a group of lines |
| Line | Text.Line | One line of text |
| Element | Text.Element | Roughly one word |
| Symbol | Text.Symbol | One character |
Think of it like a book. The Text is the page, blocks are paragraphs, lines are lines, and elements are words. Each level also gives you a bounding box, so you can draw rectangles around the text later.
Which scripts and languages are supported? (Important for Bangla readers)
As of November 2026, the official language list supports five scripts: Latin, Chinese, Devanagari, Japanese and Korean.
Bengali (Bangla) script is not supported. If you scan a Bangla newspaper, ML Kit will not give you correct Bangla text. English text on the same page will work fine.
Warning: Devanagari (used for Hindi, Marathi and Nepali) looks a little similar to Bangla, but it is a different script. The Devanagari model will not read Bangla correctly.
If you need Bangla OCR, here are some alternatives:
- Cloud OCR, such as Google Cloud Vision API text detection. It needs internet and may cost money after a free quota.
- Tesseract OCR with the Bengali trained data file (
ben.traineddata). It runs offline, but setup on Android takes more work, and accuracy depends a lot on image quality.
For English receipts, business cards, notices and documents, ML Kit is an excellent choice. Let's build.
Step 1: Add the ML Kit Text Recognition Dependency
ML Kit gives you two ways to add the Latin text model. Here are the current versions from the official Android guide, as of November 2026:
| Option | Dependency | Model location |
|---|---|---|
| Bundled | com.google.mlkit:text-recognition:16.0.1 | Inside your APK |
| Unbundled | com.google.android.gms:play-services-mlkit-text-recognition:19.0.2 | Downloaded by Google Play services |
Bundled works right away, even offline on first launch, but makes your app bigger. Unbundled keeps your app small, but the model is downloaded later. Until the download finishes, recognition returns no results.
For a beginner project, I recommend the bundled version. Open app/build.gradle.kts:
android {
defaultConfig {
minSdk = 23 // ML Kit text recognition needs API 23 or higher
}
}
dependencies {
// ML Kit Text Recognition v2 (Latin script, bundled model)
implementation("com.google.mlkit:text-recognition:16.0.1")
// Lets us call .await() on Google Play Tasks inside coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.11.0")
// ViewModel + lifecycle-aware state collection for Compose
implementation("androidx.lifecycle:lifecycle-viewmodel-compose:2.11.0")
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.11.0")
}
Let's understand it:
minSdk = 23is required by the ML Kit text recognition API.text-recognitionis the bundled Latin model.kotlinx-coroutines-play-servicesadds anawait()function forTaskobjects. ML Kit returns aTask, so this turns callbacks into simple coroutine code.- 2.11.0 was the latest stable lifecycle version when I wrote this. If Android Studio suggests a newer one, it's safe to update.
Tip: If you choose the unbundled version, add this inside
<application>inAndroidManifest.xmlso the model downloads when the app is installed:<meta-data android:name="com.google.mlkit.vision.DEPENDENCIES" android:value="ocr" />
Step 2: Design the UI State
Before writing logic, let's decide what the screen needs to show. I like to keep everything in one data class:
data class TextBlockUi(
val text: String,
val lines: List<String>
)
data class TextScanUiState(
val isLoading: Boolean = false,
val fullText: String = "",
val blocks: List<TextBlockUi> = emptyList(),
val errorMessage: String? = null,
val hasScanned: Boolean = false
)
Let's understand it:
TextBlockUiis our own simple class. We do not pass ML Kit objects to the UI, so the UI stays clean and easy to test.hasScannedhelps us show "No text found" only after a real scan.
This pattern is explained in detail in Loading and Error States in Jetpack Compose.
Step 3: Run ML Kit Text Recognition in a ViewModel
Now the main part. The ViewModel loads the image, runs the recognizer, and updates the state.
class TextScanViewModel(application: Application) : AndroidViewModel(application) {
private val recognizer: TextRecognizer =
TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
private val _uiState = MutableStateFlow(TextScanUiState())
val uiState: StateFlow<TextScanUiState> = _uiState.asStateFlow()
fun recognizeText(uri: Uri) {
viewModelScope.launch {
_uiState.value = TextScanUiState(isLoading = true)
try {
val image = withContext(Dispatchers.IO) {
InputImage.fromFilePath(getApplication(), uri)
}
val result: Text = recognizer.process(image).await()
_uiState.value = TextScanUiState(
fullText = result.text,
blocks = result.textBlocks.map { block ->
TextBlockUi(
text = block.text,
lines = block.lines.map { it.text }
)
},
hasScanned = true
)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
_uiState.value = TextScanUiState(
errorMessage = e.message ?: "Could not read text from this image.",
hasScanned = true
)
}
}
}
override fun onCleared() {
recognizer.close()
super.onCleared()
}
}
Let's understand it:
TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)creates the Latin recognizer. For other scripts you would use options such asDevanagariTextRecognizerOptionswith the matching dependency.- We use
AndroidViewModelbecauseInputImage.fromFilePath()needs aContext. The application context is safe to keep in a ViewModel. An Activity context is not. InputImage.fromFilePath(context, uri)reads the image and handles its rotation. It can throw anIOException, and it reads from storage, so we run it onDispatchers.IO.recognizer.process(image)returns aTask<Text>. Thanks toawait(), we wait for it like a normal suspend function. No nested callbacks.- We rethrow
CancellationExceptionso coroutine cancellation keeps working correctly. onCleared()closes the recognizer and frees its resources when the screen is gone for good.
Tip: If something goes wrong, use Logcat to print
ein the catch block. My post on debugging Android apps with Logcat shows how to filter logs quickly.
Step 4: Pick an Image with the Photo Picker
The Photo Picker is the modern way to choose images. The user selects one photo, and your app gets access to only that photo. No storage permission is needed.
@Composable
fun TextScanScreen(viewModel: TextScanViewModel = viewModel()) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
val context = LocalContext.current
val pickImageLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia()
) { uri: Uri? ->
if (uri != null) {
viewModel.recognizeText(uri)
}
}
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Button(
onClick = {
pickImageLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
},
enabled = !state.isLoading
) {
Text("Pick a photo")
}
Spacer(Modifier.height(16.dp))
when {
state.isLoading -> CircularProgressIndicator()
state.errorMessage != null -> Text(
text = state.errorMessage!!,
color = MaterialTheme.colorScheme.error
)
state.hasScanned && state.fullText.isBlank() -> Text("No text found in this photo.")
state.fullText.isNotBlank() -> RecognizedTextContent(
state = state,
onCopy = { copyToClipboard(context, state.fullText) }
)
}
}
}
Let's understand it:
rememberLauncherForActivityResultwithPickVisualMedia()opens the system photo picker. The result is aUri?. It isnullif the user cancels, so we check it.PickVisualMedia.ImageOnlyhides videos, because we only want images.- The button is disabled while loading, so the user cannot start two scans at once.
- The
whenblock shows exactly one state: loading, error, empty, or success.
Note: On older devices without the new picker, the Activity library falls back to a system document picker automatically. You do not need extra code.
Step 5: Show Blocks and Lines, and Copy the Text
Now let's display the result. We show the full text first, then each block with its lines.
@Composable
fun RecognizedTextContent(
state: TextScanUiState,
onCopy: () -> Unit
) {
LazyColumn(verticalArrangement = Arrangement.spacedBy(12.dp)) {
item {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = "Recognized text",
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.weight(1f)
)
TextButton(onClick = onCopy) { Text("Copy") }
}
SelectionContainer {
Text(state.fullText)
}
}
itemsIndexed(state.blocks) { index, block ->
Card(modifier = Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp)) {
Text(
text = "Block ${index + 1}",
style = MaterialTheme.typography.labelLarge
)
block.lines.forEach { line ->
Text("• $line")
}
}
}
}
}
}
fun copyToClipboard(context: Context, text: String) {
val clipboard = context.getSystemService(ClipboardManager::class.java)
clipboard.setPrimaryClip(ClipData.newPlainText("Recognized text", text))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
Toast.makeText(context, "Copied", Toast.LENGTH_SHORT).show()
}
}
Let's understand it:
SelectionContainerlets the user long-press and select part of the text.- Each
Cardshows one block. Seeing blocks and lines helps you understand how ML Kit "sees" the photo. ClipboardManager.setPrimaryClip()copies the text. On Android 13 (API 33) and newer, the system already shows a copy confirmation, so we only show a Toast on older versions.
Run the app, pick a photo of a printed page, and watch the text appear. That's it. You just built an AI-powered feature in about 150 lines.
Tips for Better Text Recognition Results
ML Kit is good, but the input photo matters a lot. Here is what helps:
| Problem | Fix |
|---|---|
| Blurry text | Hold the phone steady, tap to focus |
| Tiny text | Move closer so letters are bigger in the image |
| Dark photo | Use good light, avoid shadows on the paper |
| Angled paper | Shoot from straight above |
| Handwriting | Expect weaker results; ML Kit is best on printed text |
Tip: Never trust OCR output blindly for important data like money amounts or phone numbers. Show the text in an editable field so the user can fix mistakes.
Real Use Cases for ML Kit Text Recognition
Here are some ideas you can build on top of this app:
- Receipt reader: Find lines that contain a total and a number, then save expenses.
- Business card scanner: Use regular expressions to find emails and phone numbers in the lines.
- Notice board helper: Students can snap a printed class notice and copy the text into notes.
- Text-to-speech: Read recognized text aloud for people with low vision.
- Translation: Combine with ML Kit's on-device translation API to translate English text.
Privacy: why on-device matters
With the bundled model, the image is processed on the phone. You do not send it to any server. This is great for private documents like receipts and ID-style cards. Still, if you save scans or send text anywhere, say so clearly in your privacy policy, especially before you publish your app on Google Play.
Next Step: Live Text Recognition with CameraX
Picking a photo is a good start. The next level is reading text live from the camera. CameraX has an ImageAnalysis use case that gives you frames as ImageProxy objects. You create an InputImage with InputImage.fromMediaImage(mediaImage, rotationDegrees) and pass it to the same recognizer.
The key rule from the official docs: close the ImageProxy when processing finishes, or CameraX will stop sending new frames. Also, only process one frame at a time, so your app does not lag.
If you enjoy on-device AI, you will also like my upcoming posts on on-device AI with Gemini Nano and building an AI chat app with the Gemini API. And if you used an AI assistant to help write this code, read How to Use AI to Learn Programming Faster so you learn while you build.
Frequently Asked Questions
Is ML Kit text recognition free? Yes. ML Kit's on-device APIs, including text recognition, are free to use. There are no per-request charges, because everything runs on the user's phone.
Does ML Kit text recognition work offline?
Yes. With the bundled com.google.mlkit:text-recognition dependency, the model is inside your APK and works offline from the first launch. With the unbundled Play services version, the model must be downloaded once first.
Can ML Kit read Bangla (Bengali) text? No. As of November 2026, ML Kit supports Latin, Chinese, Devanagari, Japanese and Korean scripts only. For Bangla, consider a cloud OCR service or Tesseract with Bengali trained data.
Can ML Kit read handwriting? Text Recognition v2 is designed mainly for printed text. It may read neat handwriting sometimes, but results are not reliable. Test with your real images before you promise this feature to users.
Key Takeaways
- ML Kit text recognition reads text from images on-device, for free, with only a few lines of code.
- Use the bundled
com.google.mlkit:text-recognition:16.0.1for instant offline use, or the Play services version19.0.2for a smaller app (versions as of November 2026). - The Photo Picker (
PickVisualMedia) needs no storage permission. kotlinx-coroutines-play-servicesgives youawait(), so ML Kit fits nicely into a ViewModel with coroutines.- Results come as blocks, lines, elements and symbols, each with a bounding box.
- Bangla script is not supported. Use cloud OCR or Tesseract for Bangla.
- Next, try CameraX for live text recognition, and always close each
ImageProxy.
Related articles
Run AI directly on the phone with Gemini Nano and ML Kit GenAI APIs: privacy, offline use, device support, a Compose summarizer, cloud fallback and limits.
Build a secure AI chat in your Android app with Firebase AI Logic and Gemini: setup, App Check, model choice, streaming ViewModel, Compose UI and error handling.
Diagnose a faded Material 3 card, pair its foreground and background colors, and check the result in both light and dark mode.
Use SavedStateHandle to restore a Compose search query, reload its results, and test the difference between rotation and process recreation.