Zxing生成二维码并去掉白边(matrix.enclosingRectangle)

//生成二维码方法
suspend fun createQRCode(dataStr: String,size: Int):Bitmap? = withContext(Dispatchers.IO) {
        val hashTable = Hashtable<EncodeHintType,Any>()
        hashTable[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.L
        hashTable[EncodeHintType.CHARACTER_SET] = "UTF-8"
        hashTable[EncodeHintType.MARGIN] = 0

        var mutableFormatWriter = MultiFormatWriter().encode(dataStr,BarcodeFormat.QR_CODE,size,size,hashTable)
        //去掉白边
        mutableFormatWriter = deleteWhite(mutableFormatWriter)
        val width = mutableFormatWriter.width
        val height = mutableFormatWriter.height

        val pixels = IntArray(width * height)

        for (y in 0 until height){
            for (x in 0 until width){
                if (mutableFormatWriter[x,y]){
                    pixels[y * height + x] =Color.BLACK
                }else{
                    pixels[y * height + x] = Color.WHITE
                }
            }
        }

        val bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888)
        bitmap.setPixels(pixels,0,width,0,0,width,height)
        return@withContext bitmap
    }
   //读取二维码区域重新生成一个BitMatrix
   private fun deleteWhite(matrix: BitMatrix): BitMatrix{
        val rec = matrix.enclosingRectangle     //检测“纯”二维码码的封闭矩形
        val resWidth = rec[2] + 1   //宽
        val resHeight = rec[3] + 1  //高
        val resMatrix = BitMatrix(resWidth,resHeight)
        resMatrix.clear()
        for (i in 0 until  resWidth){
            for (j in 0 until resHeight){
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i,j)
            }
        }
        return resMatrix
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值