Skip to content

Instantly share code, notes, and snippets.

@marcouberti
Last active August 8, 2024 04:37
Show Gist options
  • Select an option

  • Save marcouberti/40dbbd836562b35ace7fb2c627b0f34f to your computer and use it in GitHub Desktop.

Select an option

Save marcouberti/40dbbd836562b35ace7fb2c627b0f34f to your computer and use it in GitHub Desktop.
ZLIB compression and decompression in Kotlin / Android
import java.io.ByteArrayOutputStream
import java.util.zip.Deflater
import java.util.zip.Inflater
/**
* Compress a string using ZLIB.
*
* @return an UTF-8 encoded byte array.
*/
fun String.zlibCompress(): ByteArray {
val input = this.toByteArray(charset("UTF-8"))
// Compress the bytes
// 1 to 4 bytes/char for UTF-8
val output = ByteArray(input.size * 4)
val compressor = Deflater().apply {
setInput(input)
finish()
}
val compressedDataLength: Int = compressor.deflate(output)
return output.copyOfRange(0, compressedDataLength)
}
/**
* Decompress a byte array using ZLIB.
*
* @return an UTF-8 encoded string.
*/
fun ByteArray.zlibDecompress(): String {
val inflater = Inflater()
val outputStream = ByteArrayOutputStream()
return outputStream.use {
val buffer = ByteArray(1024)
inflater.setInput(this)
var count = -1
while (count != 0) {
count = inflater.inflate(buffer)
outputStream.write(buffer, 0, count)
}
inflater.end()
outputStream.toString("UTF-8")
}
}
@jmkolbe

jmkolbe commented Oct 20, 2021

Copy link
Copy Markdown

On Android one can do this: InflaterInputStream(inputBytes.inputStream()).bufferedReader().use { it.readText() }

@klaudiodervishaj

Copy link
Copy Markdown

thank you :)

@hafiz013

hafiz013 commented Aug 8, 2024

Copy link
Copy Markdown

This support kotlin multiplatform? can compress byteArray image?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment