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

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

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

        public static Bitmap createQRCode(String str, int widthAndHeight)
                throws WriterException {
            Hashtable hints = new Hashtable();
            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;
        }
}

你可能感兴趣的:(android初级)