二维码扫描乱码的问题解决方法

本文介绍了一种解决中文字符串生成二维码后出现乱码的方法。通过设置字符集为UTF-8,并调整二维码生成过程中的参数,成功实现了中文内容正确显示的目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果有中文的字符串生成二维码被扫描,会扫描出乱码。本人在网上搜了各种资料都不管用,最后终于让我试验成功,记录下来,希望对大家有所帮助!

public final class CreateEncoding {
        private static final int BLACK = 0xff000000;

        public static Bitmap createQRCode(String str, int widthAndHeight)
                throws WriterException {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

            hints.put(EncodeHintType.MARGIN, 1);

    //      BitMatrix matrix = new MultiFormatWriter().encode(str,
    //              BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
            BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight,hints);
            int margin = 5; // 自定义白边边框宽度
            matrix = updateBit(matrix, margin); // 生成新的bitMatrix

            int width = matrix.getWidth();
            int height = matrix.getHeight();
            int[] pixels = new int[width * height];
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = BLACK;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        }

        private static BitMatrix updateBit(BitMatrix matrix, int margin) {
            int tempM = margin * 2;
            int[] rec = matrix.getEnclosingRectangle(); // 获取二维码图案的属性
            int resWidth = rec[2] + tempM;
            int resHeight = rec[3] + tempM;
            BitMatrix resMatrix = new BitMatrix(resWidth, resHeight); // 按照自定义边框生成新的BitMatrix
            resMatrix.clear();
            for (int i = margin; i < resWidth - margin; i++) { // 循环,将二维码图案绘制到新的bitMatrix中
                for (int j = margin; j < resHeight - margin; j++) {
                    if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {
                        resMatrix.set(i, j);
                    }
                }
            }
            return resMatrix;
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序编织梦想

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值