Last active
January 7, 2019 10:00
-
-
Save fb64/b61f1193c9e2b0bd71b6633a1b84c048 to your computer and use it in GitHub Desktop.
Bitmap extension to compresse Bitmap to ByteArray with a maximum size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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