Android Convert OutputStream to InputStream

Solution 1: ByteArray

val outputStream = ByteArrayOutputStream()outputStream.use { outputStream ->    // write to output stream    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream)    val inputStream = ByteArrayInputStream(outputStream.toByteArray())}

NOTE: toByteArray will trigger copy, thus double memory usage. Could consider this solution https://github.com/nickrussler/ByteArrayInOutStream

Solution 2: Pipe

val inputStream = PipedInputStream()val outputStream = PipedOutputStream(inputStream)// using coroutines: need to launch this in a threadlaunch(Dispatchers.Default) {    outputStream.use { outputStream ->        // outputStream will not be written/complete until the inputStream is read        bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream)    }}// TODO: read inputStream

Solution 3: okio

val buffer = Buffer()buffer.use {    // write to output stream    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outputStream)    val inputStream = buffer.inputStream()}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.