Skip to content

Instantly share code, notes, and snippets.

@Tonnie-Dev
Last active November 7, 2025 14:46
Show Gist options
  • Select an option

  • Save Tonnie-Dev/42e5c218702b207cb3529b290f27447b to your computer and use it in GitHub Desktop.

Select an option

Save Tonnie-Dev/42e5c218702b207cb3529b290f27447b to your computer and use it in GitHub Desktop.
Saving Displayed QR Code as PNG
private fun saveQrImage(
context: Context,
qrData: QrData,
scope: CoroutineScope,
showSuccessSnackbar: () -> Unit,
showErrorSnackbar: () -> Unit,
) {
scope.launch(Dispatchers.IO) {
val resolver = context.contentResolver
val fileName = "${qrData.displayName.ifBlank { "qr_code" }}.png"
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
put(MediaStore.MediaColumns.MIME_TYPE, "image/png")
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
}
val success = try {
val imageUri = resolver.insert(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
contentValues
) ?: throw IllegalStateException("Failed to create MediaStore record")
resolver.openOutputStream(imageUri)
?.use { outputStream ->
val qrBitmap = generateQrBitmap(qrData.prettifiedData)
qrBitmap.compress(
Bitmap.CompressFormat.PNG, 100,
outputStream
)
} ?: throw IllegalStateException("Failed to open output stream")
true
} catch (e: Exception) {
false
}
withContext(Dispatchers.IO) {
if (success) showSuccessSnackbar() else showErrorSnackbar()
}
}
}
// uses Zxing
fun generateQrBitmap(
data: String,
sizePx: Int = 512,
marginModules: Int = 2,
errorCorrection: ErrorCorrectionLevel = ErrorCorrectionLevel.M
): Bitmap {
val hints = mapOf(
EncodeHintType.CHARACTER_SET to "UTF-8",
EncodeHintType.ERROR_CORRECTION to errorCorrection,
EncodeHintType.MARGIN to marginModules
)
val matrix = QRCodeWriter().encode(
data,
BarcodeFormat.QR_CODE,
sizePx,
sizePx,
hints
)
return createBitmap(sizePx, sizePx)
.apply {
for (y in 0 until sizePx) {
for (x in 0 until sizePx) {
setPixel(x, y, if (matrix[x, y]) 0xFF000000.toInt() else 0xFFFFFFFF.toInt())
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment