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()}