Android 生成二维码

一、生成二维码工具类封装

1、二维码库

复制代码
  // 二维码
    implementation 'com.journeyapps:zxing-android-embedded:4.3.0'

2、工具类

复制代码
/**
 * 二维码
 * 处理工具
 */

public class QRCodeDealUtils {

    /**
     * @param content     字符串内容
     * @param size        位图宽&高(单位:px)
     * @param logo        二维码logo
     * @param logoPercent 二维码logo的占比 [0,1]
     * @return
     */
    public static Bitmap createQRCodeBitmapLogo(String content, int size, Bitmap logo, float logoPercent) {
        Bitmap qrCodeBitmap = null;
        Bitmap bitmap;
        try {
            // 不带logo二维码
            qrCodeBitmap = generateQRCodeWithoutMargin(content, size, size);
            // 带logo 二维码
            bitmap = addLogoToQRCode(qrCodeBitmap, logo, logoPercent);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }

        return bitmap;
    }


    /**
     * 生成
     * 无白色边框
     * 二维码
     */
    public static Bitmap generateQRCodeWithoutMargin(String text, int width, int height) throws WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.MARGIN, 0); // 设置边距为0

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        int[] pixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (bitMatrix.get(x, y)) {
                    pixels[y * width + x] = Color.BLACK; // 黑色像素
                } else {
                    pixels[y * width + x] = Color.TRANSPARENT; // 透明像素,去除白边
                }
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

        return bitmap;
    }

    /**
     * 给二维码
     * 添加logo
     */
    public static Bitmap addLogoToQRCode(Bitmap srcBitmap, Bitmap logoBitmap, float logoPercent) {
        // 计算Logo相对于二维码的尺寸
        int logoWidth = Math.round(srcBitmap.getWidth() * logoPercent);
        int logoHeight = Math.round(srcBitmap.getHeight() * logoPercent);

        // 确保Logo尺寸不会超过二维码尺寸
        if (logoWidth > srcBitmap.getWidth() || logoHeight > srcBitmap.getHeight()) {
            throw new IllegalArgumentException("Logo size is too large for the QR code.");
        }

        // 创建一个新的Bitmap来保存带Logo的二维码
        Bitmap resultBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig());
        Canvas canvas = new Canvas(resultBitmap);

        // 绘制原始二维码
        canvas.drawBitmap(srcBitmap, 0, 0, null);

        // 创建一个Matrix对象来缩放Logo
        Matrix matrix = new Matrix();
        matrix.postScale(logoWidth / (float) logoBitmap.getWidth(),
                logoHeight / (float) logoBitmap.getHeight());

        // 计算Logo应该放置的位置(中心)
        int xOffset = (srcBitmap.getWidth() - logoWidth) / 2;
        int yOffset = (srcBitmap.getHeight() - logoHeight) / 2;

        // 在二维码上绘制Logo
        canvas.drawBitmap(logoBitmap, xOffset, yOffset, null);

        return resultBitmap;
    }


}

二、方法说明

复制代码
   /**
     * 生成
     * 无白色边框
     * 二维码
     */
    public static Bitmap generateQRCodeWithoutMargin(String text, int width, int height) throws WriterException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.MARGIN, 0); // 设置边距为0

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        int[] pixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (bitMatrix.get(x, y)) {
                    pixels[y * width + x] = Color.BLACK; // 黑色像素
                } else {
                    pixels[y * width + x] = Color.TRANSPARENT; // 透明像素,去除白边
                }
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

        return bitmap;
    }

2、给二维码添加logo的方法

复制代码
   /**
     * 给二维码
     * 添加logo
     */
    public static Bitmap addLogoToQRCode(Bitmap srcBitmap, Bitmap logoBitmap, float logoPercent) {
        // 计算Logo相对于二维码的尺寸
        int logoWidth = Math.round(srcBitmap.getWidth() * logoPercent);
        int logoHeight = Math.round(srcBitmap.getHeight() * logoPercent);

        // 确保Logo尺寸不会超过二维码尺寸
        if (logoWidth > srcBitmap.getWidth() || logoHeight > srcBitmap.getHeight()) {
            throw new IllegalArgumentException("Logo size is too large for the QR code.");
        }

        // 创建一个新的Bitmap来保存带Logo的二维码
        Bitmap resultBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig());
        Canvas canvas = new Canvas(resultBitmap);

        // 绘制原始二维码
        canvas.drawBitmap(srcBitmap, 0, 0, null);

        // 创建一个Matrix对象来缩放Logo
        Matrix matrix = new Matrix();
        matrix.postScale(logoWidth / (float) logoBitmap.getWidth(),
                logoHeight / (float) logoBitmap.getHeight());

        // 计算Logo应该放置的位置(中心)
        int xOffset = (srcBitmap.getWidth() - logoWidth) / 2;
        int yOffset = (srcBitmap.getHeight() - logoHeight) / 2;

        // 在二维码上绘制Logo
        canvas.drawBitmap(logoBitmap, xOffset, yOffset, null);

        return resultBitmap;
    }

3、调用方式

复制代码
/**
     * @param content     字符串内容
     * @param size        位图宽&高(单位:px)
     * @param logo        二维码logo
     * @param logoPercent 二维码logo的占比 [0,1]
     * @return
     */
    public static Bitmap createQRCodeBitmapLogo(String content, int size, Bitmap logo, float logoPercent) {
        Bitmap qrCodeBitmap = null;
        Bitmap bitmap;
        try {
            // 不带logo二维码
            qrCodeBitmap = generateQRCodeWithoutMargin(content, size, size);
            // 带logo 二维码
            bitmap = addLogoToQRCode(qrCodeBitmap, logo, logoPercent);
        } catch (WriterException e) {
            throw new RuntimeException(e);
        }

        return bitmap;
    }

到此结束

相关推荐
安卓开发者6 小时前
Android RxJava 组合操作符实战:优雅处理多数据源
android·rxjava
阿华的代码王国6 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
一条上岸小咸鱼6 小时前
Kotlin 基本数据类型(三):Booleans、Characters
android·前端·kotlin
Jerry说前后端7 小时前
RecyclerView 性能优化:从原理到实践的深度优化方案
android·前端·性能优化
alexhilton7 小时前
深入浅出着色器:极坐标系与炫酷环形进度条
android·kotlin·android jetpack
一条上岸小咸鱼13 小时前
Kotlin 基本数据类型(一):Numbers
android·前端·kotlin
Huntto14 小时前
最小二乘法计算触摸事件速度
android·最小二乘法·触摸事件·速度估计
一笑的小酒馆14 小时前
Android中使用Compose实现各种样式Dialog
android
红橙Darren14 小时前
手写操作系统 - 编译链接与运行
android·ios·客户端
鹏多多.18 小时前
flutter-使用device_info_plus获取手机设备信息完整指南
android·前端·flutter·ios·数据分析·前端框架