Skip to content

Instantly share code, notes, and snippets.

@fb64
Last active January 7, 2019 10:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fb64/b61f1193c9e2b0bd71b6633a1b84c048 to your computer and use it in GitHub Desktop.
Save fb64/b61f1193c9e2b0bd71b6633a1b84c048 to your computer and use it in GitHub Desktop.
Bitmap extension to compresse Bitmap to ByteArray with a maximum size
import android.graphics.Bitmap
import java.io.ByteArrayOutputStream
fun Bitmap.compressToByteArray(maxSize: Long, stepQuality: Int = 5): ByteArray? {
try {
val byteArrayOutputStream = ByteArrayOutputStream()
var compressionQuality = 100
var byteArray: ByteArray?
do {
if (compressionQuality <= 0) return null
byteArrayOutputStream.reset()
this.compress(Bitmap.CompressFormat.JPEG, compressionQuality, byteArrayOutputStream)
byteArray = byteArrayOutputStream.toByteArray()
compressionQuality -= stepQuality
} while (byteArray != null && byteArray.size > maxSize)
return byteArray
} catch (ex: Exception) {
return null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment