How to convert a Base64 string into a Bitmap image to show it in a ImageView?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Displaying a Base64-encoded image in an Android ImageView is a two-step process: decode the string into bytes, then decode those bytes into a Bitmap. The basic code is short, but production-quality handling needs to account for malformed input, optional data-URI prefixes, and memory usage for large images.
The Basic Conversion
If you already have a plain Base64 string for a PNG or JPEG, the core logic looks like this in Kotlin:
Then assign the result to an ImageView:
That is the essential conversion.
Handling Data URI Prefixes
Many APIs and web-originated payloads include a prefix such as:
Android's Base64.decode() cannot use that whole string directly. Strip the metadata first:
Then decode:
Without this cleanup step, decoding often fails with IllegalArgumentException.
A Safer Utility Function
For app code, it is better to wrap the operation in a helper that handles malformed strings gracefully.
Usage:
This avoids crashing the UI if the incoming data is not valid Base64.
Large Images and Memory
The real problem often is not decoding. It is decoding too much. If the Base64 payload represents a very large image, converting it directly into a full bitmap can consume a lot of memory and trigger OutOfMemoryError.
For oversized images, decode with sampling:
This reduces memory by loading a smaller bitmap. It is especially useful for thumbnails or list items.
Background Threading
Base64 decoding plus bitmap creation can be expensive enough to cause UI jank if done repeatedly on the main thread. In modern Android code, move the work to a coroutine on a background dispatcher and return the result to the UI thread.
The key idea is simple: decode off the main thread, then assign the bitmap on the main thread.
Common Pitfalls
The most common mistake is feeding a full data URI into Base64.decode() without stripping the prefix. The conversion then fails even though the underlying image bytes are fine.
Another mistake is assuming every Base64 string is an image. Some payloads are empty, truncated, or encoded with unexpected flags.
Large images are another frequent source of trouble. Decoding a huge bitmap directly into memory can crash the app or make scrolling choppy.
Finally, if you load many images or remote image data frequently, consider whether a full-featured image-loading library is a better fit than hand-written Base64 decoding in UI code.
Summary
- Decode Base64 into bytes, then decode the bytes into a
Bitmap. - Strip any
data:image/...;base64,prefix before decoding. - Return
nullor a fallback image for malformed input instead of crashing. - Use sampled decoding for large images to reduce memory pressure.
- Move heavy decoding work off the main thread for smoother UI behavior.

