zxing生成二维码

本文介绍了一个使用ZXing库生成二维码的实用工具类。该工具类提供了创建二维码的方法,并允许设置二维码的颜色、尺寸及纠错级别等参数。此外还支持在二维码中嵌入Logo。

zxing生成二维码

public class QrCodeUtil {
    public static Bitmap creaQrCode(String content, int qrWidth, int qrHeight) {
        return createQrCode(content, "utf-8", Color.BLACK, qrWidth, qrHeight, ErrorCorrectionLevel.H, null);
    }

    public static Bitmap createQrCode(String content, String characterSet, int qrColor, int qrWidth, int qrHeight
            , ErrorCorrectionLevel ecl, Bitmap logo) {
        if (content == null) {
            return null;
        }
        if (characterSet == null) {
            characterSet = "utf-8";
        }
        if (ecl == null) {
            ecl = ErrorCorrectionLevel.H;
        }
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, characterSet);
        hints.put(EncodeHintType.ERROR_CORRECTION, ecl);
        hints.put(EncodeHintType.MARGIN, 0);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrWidth, qrHeight, hints);
            int[] piexs = new int[qrWidth * qrHeight];
            for (int y = 0; y < qrHeight; y++) {
                for (int x = 0; x < qrWidth; x++) {
                    if (bitMatrix.get(x, y)) {
                        piexs[y * qrWidth + x] = qrColor;
                    } else {
                        piexs[y * qrWidth] = 0xffffffff;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(qrWidth, qrHeight, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(piexs, 0, qrWidth, 0, 0, qrWidth, qrHeight, true, null);
            if (logo != null) {
                int logoHeight = qrHeight / 5;
                int logoWidth = qrWidth / 5;
                canvas.drawBitmap(genThumbnails(logo, logoWidth, logoHeight), (qrWidth - logoWidth) / 2.0f, (qrHeight - logoHeight) / 2.0f, null);
            }
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Bitmap genThumbnails(Bitmap logo, int logoWidth, int logoHeight) {
        if (logo == null || logoHeight < 0 || logoWidth < 0) {
            throw new IllegalArgumentException();
        }
        Bitmap bitmap = Bitmap.createBitmap(logoWidth, logoHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(Bitmap.createScaledBitmap(logo, logoWidth - 10, logoHeight - 10, false), 5, 5, null);
        return bitmap;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值