It started with a small favor: a friend had 200+ HEIC photos on his phone and the print shop only accepted JPG. He tried three “free converters” from the Play Store — the first stamped a watermark on everything, the second crashed halfway, the third rotated all his portrait shots to landscape. So I spent one evening writing my own little tool. This post is the post-mortem of that evening.
What I learned: file conversion has two buttons on the surface and all the traps underneath. Users want “pick file, hit convert, get result” — but underneath you’re handling URI permission lifecycles, scoped-storage export paths, decode-time memory spikes, EXIF orientation, and format fragmentation across devices. Anyone can draw buttons; making the whole input-to-output chain reliable is the actual skill.
The Problem
First, accept one fact: the system doesn’t give you a file — it gives you an expiring URI. The Storage Access Framework returns content:// URIs that aren’t guaranteed to survive a process restart. The correct move is to call takePersistableUriPermission immediately and read through ContentResolver.openInputStream. Never write File(uri.path) — it crashes 9 times out of 10, and the 10th time it’ll be on your advisor’s demo phone.
Export paths changed rules after scoped storage. Since Android 10, external storage is partitioned: write to Downloads via MediaStore, or to getExternalFilesDir with no permission at all — but those files vanish when the app is uninstalled. Pick the wrong location and you get a darkly funny outcome: the conversion succeeded, but the user can’t find the file. That damages trust more than a clean failure.
Decoding is the real memory killer. A 12MP photo decoded as ARGB_8888 is 12M × 4 bytes ≈ 48MB. Convert a few in a row and the main thread OOMs. Two countermeasures: downsample first with inSampleSize, and chew through huge images in tiles with BitmapRegionDecoder.
Then there’s EXIF orientation, the sneaky one. Portrait shots are stored as landscape pixels — the EXIF ORIENTATION tag is what tells the gallery to “display rotated 90°.” Skip that tag during conversion and every portrait comes out sideways. That’s exactly how my friend got 200 sideways “portraits.” Read the orientation with ExifInterface, rotate with a Matrix, then compress — in that order, never reversed.
The Approach
Routing is the heart of the whole design. The rule is simple: millisecond-scale, deterministic jobs run locally; heavy, long-tail formats go to the cloud; batch jobs always go through a queue.
- On-device: image conversion (JPG / PNG / WebP / AVIF), HEIC decode (Android 9+), PDF-to-image and merging — offline, low latency, data never leaves the phone
- Cloud: PDF-to-Word (involves reflow), video transcoding, OCR — full format coverage and fast to build, but mind the network and the bill
- Batch (20+ files): always into a WorkManager queue, processed serially with a notification progress bar — survives process death
Hook up the file picker with a persisted permission — “register” the URI the moment you get it:
val pickFile = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
uri ?: return@registerForActivityResult
contentResolver.takePersistableUriPermission(
uri, Intent.FLAG_GRANT_READ_URI_PERMISSION
)
viewModel.enqueue(uri, targetFormat = "png")
}
The core on-device image conversion — EXIF rotation must happen before compression:
fun convertToPng(context: Context, uri: Uri, outFile: File) {
val opts = BitmapFactory.Options().apply { inSampleSize = 2 } // compute from source size
context.contentResolver.openInputStream(uri)?.use { input ->
val bmp = BitmapFactory.decodeStream(input, null, opts)
?: error("decode failed: $uri")
val oriented = applyExifRotation(context, uri, bmp)
FileOutputStream(outFile).use { fos ->
oriented.compress(Bitmap.CompressFormat.PNG, 100, fos)
}
if (oriented !== bmp) bmp.recycle()
}
}
fun applyExifRotation(context: Context, uri: Uri, bmp: Bitmap): Bitmap {
val orientation = context.contentResolver.openInputStream(uri)?.use { input ->
ExifInterface(input).getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL
)
} ?: return bmp
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
else -> return bmp
}
return Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, matrix, true)
}
In the Compose layer I do exactly one thing: pin down the state machine. Five states — Idle / Queued / Converting / Done / Failed — each with its own screen. The failure screen always carries a retry button and the raw error — never a Toast that vanishes in two seconds.
sealed interface ConvertState {
data object Idle : ConvertState
data class Queued(val position: Int) : ConvertState
data class Converting(val progress: Float) : ConvertState
data class Done(val outputUri: Uri) : ConvertState
data class Failed(val reason: String, val retry: () -> Unit) : ConvertState
}
Output filenames follow a "${stem}_${yyyyMMdd_HHmmss}.${ext}" template, with illegal characters (\/:*?"<>|) stripped from the stem first. Stable and recognizable beats clever — if users can spot the file in their file manager at a glance, that’s the best UX there is.
The Result
Measured on a mid-range phone (Pixel 6a class):
- 12MP JPG → PNG: median 380ms, P90 620ms — on-device image conversion feels like “tap and it’s done”
- HEIC → JPG: ~1.1s average on Android 12+; on pre-Android 9 devices it doesn’t even try — automatic cloud fallback
- Batch of 50: WorkManager serial queue + notification progress; kill the process mid-way and it resumes on return; failures land in a “failed list” with one-tap retry; originals untouched throughout
- OOM crashes: after capping inSampleSize and adding tiled decoding for huge images, related crashes went from double digits per week to zero
The moment I’m proudest of isn’t the speed — it’s what my friend said afterwards: “at least yours tells me why it failed.” Trust is that plain.
The State of Things
Android 14 added partial photo access — users grant just the photos they pick — which actually makes the SAF flow smoother, since it was already per-URI grants. AVIF is replacing WebP as the new default; HEIC is a non-issue on new phones.
On the cloud side, cost is the eternal headline: video transcoding bills by the minute, OCR by the call — do the math before you price anything. Next on my list: localizing transcoding with Media3 — if 1080p clips can transcode on-device, the cloud bill gets cut dramatically.
Hands-On Tonight
- New project. Wire up
ActivityResultContracts.OpenDocument()in MainActivity, calltakePersistableUriPermissionthe moment you get a URI, print its authority and confirm you're holding a content:// URI, not file:// - Write
convertToPng()+applyExifRotation()from the snippets above, run one portrait phone photo through it, and check the output orientation - Draw the five ConvertState states as five Compose screens — spend the most care on Failed: raw error text + retry button, both non-negotiable
- Batch: process 20 images serially with WorkManager OneTimeWorkRequest, hang progress on a notification with setProgress, kill the process yourself, and verify it resumes
- Add routing fallback: on
Build.VERSION.SDK_INT < 28devices, mark HEIC jobs as "needs network conversion" instead of letting old phones hard-decode and crash
FAQ
How do I choose between on-device and cloud?
Look at three things: latency requirements, format complexity, cost. Millisecond-scale deterministic jobs (image conversion, HEIC decode, PDF-to-image) go local; PDF reflow, video transcoding, OCR go to the cloud. My default is hybrid — simple formats locally, complex ones in the cloud — closest to a real product.
Why can’t I just use File(uri.path)?
SAF returns content:// URIs that don’t necessarily map to real file paths — a File built from uri.path almost never exists. Read via ContentResolver.openInputStream(uri) and extend the permission with takePersistableUriPermission.
My converted photos come out rotated — how do I fix it?
Read the EXIF ORIENTATION tag and rotate with a Matrix before compressing. Order matters: decode → rotate → compress.
Does batch conversion survive process death?
With a WorkManager serial queue, yes. It’s system-level scheduling — the system re-schedules the task after a kill. Combined with notification progress and a failed list, users perceive “it paused for a moment,” not “everything is gone.”
What about HEIC on old phones?
Pre-Android 9 has no system HEIC decoder — don’t force it. Downgrade in the routing table: HEIC jobs on those devices go to the cloud, or just tell the user plainly “this phone isn’t supported.” Both beat a crash.
The X-thread version
1/ File conversion on Android: the buttons are 5% of the work, the other 95% is boundaries — expiring URIs, memory-hungry decoding, HEIC that won’t open on old phones. This is the post-mortem of converting 200 HEIC photos for a friend 🧵 2/ Trap #1: SAF doesn’t give you a file — it gives you a content:// URI that expires. Call takePersistableUriPermission immediately to “register” it, read via openInputStream. File(uri.path) crashes 9 times out of 10. 3/ Trap #2: a 12MP photo decoded as ARGB_8888 ≈ 48MB of RAM. Convert a few in a row and boom, OOM. Fix: downsample with inSampleSize first, chew huge images in tiles with BitmapRegionDecoder. 4/ Trap #3: portrait photos come out sideways. Culprit: the EXIF ORIENTATION tag — pixels are stored landscape. Decode → Matrix rotate → compress. Never reverse the order. 5/ Routing table: image conversion / HEIC decode / PDF-to-image run locally (millisecond, offline); PDF reflow / video transcoding / OCR go to the cloud; 20+ files always enter a WorkManager queue. 6/ Measured numbers (Pixel 6a class): 12MP JPG→PNG median 380ms; HEIC→JPG ~1.1s on Android 12+; after the downsampling guardrails, OOM crashes went to zero. 7/ The Compose layer does one thing: pin down Idle/Queued/Converting/Done/Failed. The failure screen always has a retry button and the raw error — never a 2-second Toast. 8/ Hands-on tonight: ① OpenDocument + persist the URI permission ② convertToPng with EXIF rotation on a portrait shot ③ five states as five screens ④ WorkManager batch of 20, kill the process, verify resume. 9/ Trust is plain like that — my friend said “at least yours tells me why it failed.” Full post + code: https://citygenius-blog.pages.dev/article/android-file-conversion
去年帮朋友干过一件小事:他手机里 200 多张 HEIC 照片,打印店说只收 JPG。在应用商店下了三个”免费转换器”,第一个转完偷偷加水印,第二个转到一半闪退,第三个把竖拍的照片全转成了横的。最后我花一晚上自己写了个小工具——这篇文章就是那晚上的复盘。
做完我才发现,文件转换这个需求,页面上就两个按钮,坑全在看不见的地方。用户要的是”选文件、点转换、拿结果”,但底下要过五关:URI 的权限生命周期、分级存储的导出路径、解码的内存峰值、EXIF 的方向信息、不同机型的格式碎片化。按钮谁都会画,把整条输入到输出的链路做靠谱才是本事。
问题
先接受一个事实:系统给你的不是文件,是一个会过期的 URI。Storage Access Framework 返回的是 content:// 开头的 URI,它不保证进程重启后还有效。正确姿势是拿到手立刻 takePersistableUriPermission,再用 ContentResolver.openInputStream 读流。千万别写 File(uri.path)——10 次里 9 次崩,剩下 1 次在你导师的演示机上崩。
分级存储之后,导出路径也换了规则。Android 10 起外部存储分区:往 Download 写走 MediaStore,往 getExternalFilesDir 写不用申请任何权限,但应用一卸载文件跟着没。选错位置的后果很黑色幽默:转换成功了,用户找不到文件,比转失败更伤信任。
解码是真正的内存杀手。一张 1200 万像素的照片,用 ARGB_8888 解码就是 1200 万 × 4 字节 ≈ 48MB。批量转几张,主线程直接 OOM。对策就两条:先用 inSampleSize 降采样解码,超大图走 BitmapRegionDecoder 分块啃。
还有 EXIF 方向这个老六。手机竖拍的照片,像素本身是横着存的,全靠 EXIF 里的 ORIENTATION tag 告诉相册”旋转 90 度显示”。转换时不读这个 tag,输出必横——我朋友那 200 张”横过来的竖拍”就是这么来的。用 ExifInterface 读方向,Matrix 旋转后再 compress,顺序不能反。
做法
路由决策是整套方案的心脏。原则很简单:毫秒级、确定性的活本地做;重型、长尾格式上云;批量任务一律进队列。
- 本地:图片互转(JPG / PNG / WebP / AVIF)、HEIC 解码(Android 9+)、PDF 转图片与合并 —— 离线可用、延迟低、隐私不出设备
- 云端:PDF 转 Word(涉及重排版)、视频转码、OCR —— 格式能力全、实现快,但要算网络和成本账
- 批量(超过 20 个文件):一律进 WorkManager 队列串行跑,通知栏挂进度,杀进程后能续跑
文件选择器接上持久权限,拿到 URI 当场”上户口”:
val pickFile = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
uri ?: return@registerForActivityResult
contentResolver.takePersistableUriPermission(
uri, Intent.FLAG_GRANT_READ_URI_PERMISSION
)
viewModel.enqueue(uri, targetFormat = "png")
}
本地图片转换的核心函数,EXIF 旋转必须发生在压缩之前:
fun convertToPng(context: Context, uri: Uri, outFile: File) {
val opts = BitmapFactory.Options().apply { inSampleSize = 2 } // 按原图尺寸动态计算
context.contentResolver.openInputStream(uri)?.use { input ->
val bmp = BitmapFactory.decodeStream(input, null, opts)
?: error("decode failed: $uri")
val oriented = applyExifRotation(context, uri, bmp)
FileOutputStream(outFile).use { fos ->
oriented.compress(Bitmap.CompressFormat.PNG, 100, fos)
}
if (oriented !== bmp) bmp.recycle()
}
}
fun applyExifRotation(context: Context, uri: Uri, bmp: Bitmap): Bitmap {
val orientation = context.contentResolver.openInputStream(uri)?.use { input ->
ExifInterface(input).getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL
)
} ?: return bmp
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180f)
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270f)
else -> return bmp
}
return Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.height, matrix, true)
}
Compose 层我只做一件事:把状态机钉死。Idle / Queued / Converting / Done / Failed 五个状态,每个都有对应的界面,失败那一页永远带”重试”按钮和错误原文——而不是一个 2 秒就消失的 Toast。
sealed interface ConvertState {
data object Idle : ConvertState
data class Queued(val position: Int) : ConvertState
data class Converting(val progress: Float) : ConvertState
data class Done(val outputUri: Uri) : ConvertState
data class Failed(val reason: String, val retry: () -> Unit) : ConvertState
}
导出文件名用 "${stem}_${yyyyMMdd_HHmmss}.${ext}" 模板,stem 先过滤掉 \/:*?"<>| 这些非法字符。稳定可识别,比什么都重要——用户在文件管理器里能一眼找到,就是最好的 UX。
结果
在一台中端机(Pixel 6a 级别)上的实测数据:
- 12MP 的 JPG 转 PNG:中位数 380ms,P90 620ms——本地转图片就是”点完就有”的体感
- HEIC 转 JPG:Android 12 以上机型均值 1.1s;Android 9 以下机型不硬解,自动降级走云端
- 批量 50 张:WorkManager 串行 + 通知栏进度,中途杀进程重进后能续跑,失败项自动进”失败列表”一键重试,原文件全程 untouched
- OOM 相关崩溃:加上 inSampleSize 上限与超大图分块解码兜底之后,相关崩溃从每周两位数清零
最让我有成就感的不是速度,是我朋友后来跟我说:“你这个至少转失败了会告诉我为什么。” 信任感就是这么朴素。
现状
Android 14 开始照片权限支持”部分授权”,用户只给你选中的几张照片——SAF 那套流程反而更顺了,因为本来就是按 URI 逐个授权的。AVIF 正在接替 WebP 成为新默认,HEIC 在新机上已经毫无压力。
云端那一侧,成本是永远的大头:视频转码按分钟计费,OCR 按次计费,定价之前先把账算清楚。下一步我想试 Media3 的转码器本地化——如果 1080p 短视频能在端上转,云端账单能砍掉一大半。
现在就能动手
- 新建项目,在 MainActivity 里用
ActivityResultContracts.OpenDocument()接一个文件选择器,拿到 URI 后立刻takePersistableUriPermission,打印它的 authority,确认你拿到的是 content:// 而不是 file:// - 照着上面的代码写出
convertToPng()+applyExifRotation(),找一张手机竖拍的照片跑通,检查输出方向是否正确 - 把 ConvertState 的五个状态画成五个 Compose 界面,重点打磨 Failed 页:错误原文展示 + 重试按钮,一个都不能少
- 批量逻辑:用 WorkManager 的 OneTimeWorkRequest 串行处理 20 张图,通知栏挂 setProgress,亲手杀一次进程,验证重进后是否续跑
- 加上路由降级:在
Build.VERSION.SDK_INT < 28的机型上,HEIC 任务直接标记"需联网转换",别让老机器硬解崩溃
常见问题
本地处理和云端 API 怎么选?
看三件事:延迟要求、格式复杂度、成本。图片互转、HEIC 解码、PDF 转图片这类毫秒级确定性任务放本地;PDF 重排版、视频转码、OCR 上云。我的默认答案是混合路由——简单格式本地做,复杂格式上云,最接近真实产品。
为什么不能直接用 File(uri.path)?
SAF 返回的是 content:// URI,背后不一定对应真实文件路径,uri.path 拼出来的 File 十有八九不存在。用 ContentResolver.openInputStream(uri) 读流,权限用 takePersistableUriPermission 续命。
转换后的照片方向错了怎么办?
读 EXIF 的 ORIENTATION tag,用 Matrix 旋转后再 compress。记住顺序:解码 → 旋转 → 压缩,旋转发生在压缩之前。
批量转换时杀进程会断吗?
用 WorkManager 做串行队列就不会。它是系统级调度,进程被杀后系统会重新调度任务,配合通知栏进度和失败列表,用户感知是”暂停了一下”而不是”全没了”。
HEIC 在老手机上打不开怎么办?
Android 9 以下没有系统级 HEIC 解码器,别硬解。路由表里直接降级:这类机型上的 HEIC 任务走云端,或者干脆明确告诉用户”这台机器不支持”,都比闪退强。
本篇的 X 速览版
1/ 在 Android 上做文件转换,按钮只占 5% 工作量,剩下 95% 全是边界:会过期的 URI、吃内存的解码、老机型打不开的 HEIC。这篇是我帮朋友转 200 张 HEIC 照片的复盘 🧵 2/ 第一个坑:SAF 给你的不是文件,是 content:// URI,还会过期。拿到手立刻 takePersistableUriPermission”上户口”,用 openInputStream 读流。File(uri.path) 十有八九直接崩。 3/ 第二个坑:1200 万像素照片 ARGB_8888 解码 ≈ 48MB 内存,连转几张就 OOM。解法:inSampleSize 降采样先行,超大图上 BitmapRegionDecoder 分块啃。 4/ 第三个坑:竖拍照片转完变横的。元凶是 EXIF 的 ORIENTATION tag——像素本身是横存的。解码→Matrix 旋转→压缩,顺序不能反。 5/ 路由决策表:图片互转/HEIC 解码/PDF 转图片走本地(毫秒级、离线);PDF 重排版/视频转码/OCR 上云;超过 20 个文件一律进 WorkManager 队列。 6/ 实测数据(Pixel 6a 级别):12MP JPG→PNG 中位数 380ms;HEIC→JPG 在 Android 12+ 上均值 1.1s;加了降采样兜底后 OOM 相关崩溃清零。 7/ Compose 层只做一件事:把 Idle/Queued/Converting/Done/Failed 五个状态钉死。失败页永远带”重试”按钮和错误原文,而不是一个 2 秒消失的 Toast。 8/ 今晚就能动手:① OpenDocument 拿 URI 并续权限 ② 写 convertToPng+EXIF 旋转跑通一张竖拍 ③ 五个状态画成五个界面 ④ WorkManager 串行 20 张并亲手杀进程验证续跑。 9/ 信任感就是这么朴素:朋友最后跟我说”你这个至少转失败了会告诉我为什么”。全文+代码:https://citygenius-blog.pages.dev/article/android-file-conversion