Skip to content

Commit

Permalink
fix: Lower the risk of OutOfMemoryError
Browse files Browse the repository at this point in the history
- Seems like we encounter this issue when we try to convert a very large byte array representing an image to a base64 string
  - Sentry reported failing to allocated 144 MB
  • Loading branch information
cyanChill committed Sep 6, 2024
1 parent 2c41bf7 commit de4fa42
Showing 1 changed file with 16 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.cyanchill.missingcore.metadataretriever

import android.util.Base64
import androidx.media3.common.MimeTypes
import java.io.ByteArrayOutputStream
import java.net.URLConnection


Expand All @@ -18,7 +19,21 @@ fun getBase64Image(bytes: ByteArray?): String? {
// Ensure the mimeType we get is defined and is for an image.
if (!MimeTypes.isImage(mimeType)) return null

return "data:$mimeType;base64,${Base64.encodeToString(bytes as ByteArray, Base64.DEFAULT)}"
// Use simplier & faster method for converting the byte array to a string based on its size (<5MB).
if (bytes.size < 5 * 1024 * 1024) {
return "data:$mimeType;base64,${Base64.encodeToString(bytes as ByteArray, Base64.DEFAULT)}"
}

// Process large byte array (>=5MB) more efficiently to prevent `OutOfMemoryError`.
val outputStream = ByteArrayOutputStream()
bytes.asSequence()
.chunked(3 * 1024 * 1024) // 4 characters usually convert to 3 bytes; so we should chunk in multiples of 3.
.forEach { chunk ->
val encodedChunk = Base64.encode(chunk.toByteArray(), Base64.NO_WRAP)
outputStream.write(encodedChunk)
}

return "data:$mimeType;base64,${outputStream.toString()}"
}

/**
Expand Down

0 comments on commit de4fa42

Please sign in to comment.