Android二维码生成与识别

导入库implementation 'com.google.zxing:core:3.4.1'

public class QrCodeUtil {
    public static String decode(Context context, Uri uri) {
        try {
            Bitmap bmp= MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
            return decode(bmp);
        } catch (Exception e) {
            return "";
        }
    }

    public static String decode(Bitmap bmp) {
        Hashtable hints=new Hashtable<>();
        hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

        try {
            int width=bmp.getWidth();
            int height=bmp.getHeight();
            int[] pixels=new int[width * height];
            bmp.getPixels(pixels, 0, width, 0, 0, width, height);

            RGBLuminanceSource source=new RGBLuminanceSource(width, height, pixels);
            return new MultiFormatReader().decode(new BinaryBitmap(new HybridBinarizer(source)), hints).getText();
        } catch (Exception e) {
            return "";
        }
    }

    public static Bitmap generate(CharSequence content, int width, int height) {
        if (TextUtils.isEmpty(content)) {
            return null;
        }
        Hashtable hints=new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix bitMatrix=new QRCodeWriter().encode(content.toString(), BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            // 下面这里按照二维码的算法,逐个生成二维码的图片,
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * width + x] = 0xffffffff;
                    }
                }
            }
            // 生成二维码图片的格式,使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }
}

你可能感兴趣的:(Android二维码生成与识别)