Skip to content

Instantly share code, notes, and snippets.

@XinyueZ
Last active April 15, 2024 08:03
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save XinyueZ/3cca89416a1e443f914ed37f80ed59f2 to your computer and use it in GitHub Desktop.
Save XinyueZ/3cca89416a1e443f914ed37f80ed59f2 to your computer and use it in GitHub Desktop.
Compare drawable or bitmap content
// Usage:
// drawable1.bytesEqualTo(drawable2)
// drawable1.pixelsEqualTo(drawable2)
// bitmap1.bytesEqualTo(bitmap1)
// bitmap1.pixelsEqualTo(bitmap2)
fun <T : Drawable> T.bytesEqualTo(t: T?) = toBitmap().bytesEqualTo(t?.toBitmap(), true)
fun <T : Drawable> T.pixelsEqualTo(t: T?) = toBitmap().pixelsEqualTo(t?.toBitmap(), true)
fun Bitmap.bytesEqualTo(otherBitmap: Bitmap?, shouldRecycle: Boolean = false) = otherBitmap?.let { other ->
if (width == other.width && height == other.height) {
val res = toBytes().contentEquals(other.toBytes())
if (shouldRecycle) {
doRecycle().also { otherBitmap.doRecycle() }
}
res
} else false
} ?: kotlin.run { false }
fun Bitmap.pixelsEqualTo(otherBitmap: Bitmap?, shouldRecycle: Boolean = false) = otherBitmap?.let { other ->
if (width == other.width && height == other.height) {
val res = Arrays.equals(toPixels(), other.toPixels())
if (shouldRecycle) {
doRecycle().also { otherBitmap.doRecycle() }
}
res
} else false
} ?: kotlin.run { false }
fun Bitmap.doRecycle() {
if (!isRecycled) recycle()
}
fun <T : Drawable> T.toBitmap(): Bitmap {
if (this is BitmapDrawable) return bitmap
val drawable: Drawable = this
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
fun Bitmap.toBytes(): ByteArray = ByteArrayOutputStream().use { stream ->
compress(Bitmap.CompressFormat.JPEG, 100, stream)
stream.toByteArray()
}
fun Bitmap.toPixels() = IntArray(width * height).apply { getPixels(this, 0, width, 0, 0, width, height) }
@MrNbody16
Copy link

that s sooooo usefull thanks

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