Skip to content

Commit 78ccb8f

Browse files
committed
Recycle bitmap after compression
1 parent dae3424 commit 78ccb8f

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

sentry-android-core/src/main/java/io/sentry/android/core/internal/util/ScreenshotUtils.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,14 @@ public class ScreenshotUtils {
164164
return null;
165165
}
166166

167+
/**
168+
* Compresses the supplied Bitmap to a PNG byte array. After compression, the Bitmap will be
169+
* recycled.
170+
*
171+
* @param bitmap The bitmap to compress
172+
* @param logger the logger
173+
* @return the Bitmap in PNG format, or null if the bitmap was null, recycled or compressing faile
174+
*/
167175
public static @Nullable byte[] compressBitmapToPng(
168176
final @Nullable Bitmap bitmap, final @NotNull ILogger logger) {
169177
if (bitmap == null || bitmap.isRecycled()) {
@@ -173,6 +181,7 @@ public class ScreenshotUtils {
173181
// 0 meaning compress for small size, 100 meaning compress for max quality.
174182
// Some formats, like PNG which is lossless, will ignore the quality setting.
175183
bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
184+
bitmap.recycle();
176185

177186
if (byteArrayOutputStream.size() <= 0) {
178187
logger.log(SentryLevel.DEBUG, "Screenshot is 0 bytes, not attaching the image.");

sentry-android-core/src/test/java/io/sentry/android/core/internal/util/ScreenshotUtilTest.kt

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import org.robolectric.Robolectric.buildActivity
1818
import org.robolectric.annotation.Config
1919
import org.robolectric.shadows.ShadowPixelCopy
2020
import kotlin.test.Test
21+
import kotlin.test.assertFalse
2122
import kotlin.test.assertNotNull
2223
import kotlin.test.assertTrue
2324

@@ -136,6 +137,14 @@ class ScreenshotUtilTest {
136137
assertNotNull(bytes)
137138
assertTrue(bytes.isNotEmpty())
138139
}
140+
141+
@Test
142+
fun `compressBitmapToPng recycles the supplied bitmap`() {
143+
val bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888)
144+
assertFalse(bitmap.isRecycled)
145+
ScreenshotUtils.compressBitmapToPng(bitmap, NoOpLogger.getInstance())
146+
assertTrue(bitmap.isRecycled)
147+
}
139148
}
140149

141150
class ExampleActivity : Activity() {

0 commit comments

Comments
 (0)