Guest User

Untitled

a guest
Jan 19th, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. // Usage:
  2. // drawable1.bytesEqualTo(drawable2)
  3. // drawable1.pixelsEqualTo(drawable2)
  4. // bitmap1.bytesEqualTo(bitmap1)
  5. // bitmap1.pixelsEqualTo(bitmap2)
  6.  
  7.  
  8. fun <T : Drawable> T.bytesEqualTo(t: T?) = toBitmap().bytesEqualTo(t?.toBitmap(), true)
  9.  
  10. fun <T : Drawable> T.pixelsEqualTo(t: T?) = toBitmap().pixelsEqualTo(t?.toBitmap(), true)
  11.  
  12. fun Bitmap.bytesEqualTo(otherBitmap: Bitmap?, shouldRecycle: Boolean = false) = otherBitmap?.let { other ->
  13. if (width == other.width && height == other.height) {
  14. val res = toBytes().contentEquals(other.toBytes())
  15. if (shouldRecycle) {
  16. doRecycle().also { otherBitmap.doRecycle() }
  17. }
  18. res
  19. } else false
  20. } ?: kotlin.run { false }
  21.  
  22. fun Bitmap.pixelsEqualTo(otherBitmap: Bitmap?, shouldRecycle: Boolean = false) = otherBitmap?.let { other ->
  23. if (width == other.width && height == other.height) {
  24. val res = Arrays.equals(toPixels(), other.toPixels())
  25. if (shouldRecycle) {
  26. doRecycle().also { otherBitmap.doRecycle() }
  27. }
  28. res
  29. } else false
  30. } ?: kotlin.run { false }
  31.  
  32. fun Bitmap.doRecycle() {
  33. if (!isRecycled) recycle()
  34. }
  35.  
  36. fun <T : Drawable> T.toBitmap(): Bitmap {
  37. if (this is BitmapDrawable) return bitmap
  38.  
  39. val drawable: Drawable = this
  40. val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
  41. val canvas = Canvas(bitmap)
  42. drawable.setBounds(0, 0, canvas.width, canvas.height)
  43. drawable.draw(canvas)
  44. return bitmap
  45. }
  46.  
  47. fun Bitmap.toBytes(): ByteArray = ByteArrayOutputStream().use { stream ->
  48. compress(Bitmap.CompressFormat.JPEG, 100, stream)
  49. stream.toByteArray()
  50. }
  51.  
  52. fun Bitmap.toPixels() = IntArray(width * height).apply { getPixels(this, 0, width, 0, 0, width, height) }
Add Comment
Please, Sign In to add comment