字符串生成二维码

implementation "com.google.zxing:core:3.3.2"
implementation "com.journeyapps:zxing-android-embedded:3.6.0"


fun createQRImage(
content: String?, widthPix: Int, heightPix: Int
): Bitmap? {
try {
val hints = HashMap<EncodeHintType, Any>()
hints[EncodeHintType.CHARACTER_SET] = StandardCharsets.UTF_8.name()
hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.L
hints[EncodeHintType.MARGIN] = 1

var bitMatrix: BitMatrix? = null
try {
bitMatrix = QRCodeWriter().encode(
content, BarcodeFormat.QR_CODE, widthPix,
heightPix, hints
)
/* bitMatrix = MultiFormatWriter().encode(
content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints
)*/

} catch (e: WriterException) {
"createQRImage WriterException=$e".logD("ljj")

}
val pixels = IntArray(widthPix * heightPix)
for (y in 0 until heightPix) {
for (x in 0 until widthPix) {
if (bitMatrix != null) {
if (bitMatrix.get(x, y)) {
pixels[y * widthPix + x] = -0x1000000
} else {
pixels[y * widthPix + x] = -0x1
}
} else {
return null
}
}
}
val bitmap: Bitmap? = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888)
bitmap!!.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix)
return bitmap
} catch (e: Exception) {
"createQRImage Exception=$e".logD("ljj")
}
return null
}
posted @ 2022-08-25 15:55  新感觉  阅读(84)  评论(0编辑  收藏  举报