Skip to content

Commit 42cc1e5

Browse files
authored
Refactor resizeImage function for better resource handling (#218)
* Refactor resizeImage function for better resource handling Refactor image resizing to use input stream safely and improve bitmap scaling. * Recycle bitmap after extracting RGB values
1 parent 2c1a094 commit 42cc1e5

1 file changed

Lines changed: 11 additions & 4 deletions

File tree

  • llm/android/LlamaDemo/app/src/main/java/com/example/executorchllamademo

llm/android/LlamaDemo/app/src/main/java/com/example/executorchllamademo/ETImage.kt

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ class ETImage(
7878
rgbValues[(y * width + x) + 2 * height * width] = blue.toByte()
7979
}
8080
}
81+
bitmap.recycle()
8182
return rgbValues
8283
} catch (e: FileNotFoundException) {
8384
throw RuntimeException(e)
@@ -87,15 +88,21 @@ class ETImage(
8788
private fun resizeImage(uri: Uri, sideSize: Int): Bitmap? {
8889
val inputStream = contentResolver.openInputStream(uri)
8990
if (inputStream == null) {
90-
ETLogging.getInstance().log("Unable to resize image, input streams is null")
91+
ETLogging.getInstance().log("Unable to resize image, input stream is null")
9192
return null
9293
}
93-
val bitmap = BitmapFactory.decodeStream(inputStream)
94+
val bitmap = inputStream.use {
95+
BitmapFactory.decodeStream(it)
96+
}
9497
if (bitmap == null) {
9598
ETLogging.getInstance().log("Unable to resize image, bitmap during decode stream is null")
9699
return null
97100
}
98-
99-
return Bitmap.createScaledBitmap(bitmap, sideSize, sideSize, false)
101+
val scaled = Bitmap.createScaledBitmap(bitmap, sideSize, sideSize, true) // ← bilinear
102+
if (scaled !== bitmap) {
103+
bitmap.recycle()
104+
}
105+
return scaled
100106
}
107+
101108
}

0 commit comments

Comments
 (0)