【android应用】基于ZXing生成的二维码,文末附带源码---添加log、彩色、背景、文字、水印在这里都能找到

最近在做一个二维码的相关的应用,顺带整理下相关的知识。今天我们来看看二维码的生成以及美化二维码(添加logo、彩色、背景、文字、水印在这里都能找到)。


第三方库

现在在实际应用中使用的最为广泛的二维码生成工具就是Zxing库,本文以Zxing-2.0版本做的研究分析。

下载方式:https://blog.csdn.net/twk121109281/article/details/93600672

加载第三方库的方法:https://blog.csdn.net/twk121109281/article/details/93601300

生成二维码

加载Zxing库后,即可直接使用该库的直接生成二维码

1、获取编码后的数据Bitmatrix

BitMatrix是Zxing库定义的一个二维码的数据类。这个方法主要是生成二维码的BitMatrix,实际上就是一个矩阵,二维数组。然后还必须设置容错率:容错率有M,L,Q,H几个等级,容错率越高,二维码的有效像素点就越多。这里使用小写的utf-8编码。

    //生成二维码
    public static Bitmap generateQRCode(String content, int width, int height) {
        try {
            HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
            // 设置编码方式utf-8
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //设置二维码的纠错级别为h
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            BitMatrix matrix = new QRCodeWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);
            //BitMatrix matrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);
            return bitMatrix2Bitmap(matrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

2、将数据Bitmatrix转换成Bitmap

这个方法将Bitmatrix获转换成Bitmap后,就可以随意展示了。

    private static Bitmap bitMatrix2Bitmap(BitMatrix matrix) {
        int WIDTH = matrix.getWidth();
        int HEIGHT = matrix.getHeight();
        int[] pixels = new int[WIDTH * HEIGHT];
        for (int y = 0; y < WIDTH; y++) {
            for (int x = 0; x < HEIGHT; x++) {
                int color = Color.WHITE;
                if (matrix.get(x, y)) {
                    // 有内容的部分,颜色设置为渐变,当然这里可以自己修改成喜欢的颜色
                    color = 0xFF0094FF + y/2;// 蓝色
//                    if (x < WIDTH / 2 && y < HEIGHT / 2) {
//                        color = 0xFF0094FF;// 蓝色
//                        //Integer.toHexString(new Random().nextInt());
//                    } else if (x < WIDTH / 2 && y > HEIGHT / 2) {
//                        color = 0xFFFED545;// 黄色
//                    } else if (x > WIDTH / 2 && y > HEIGHT / 2) {
//                        color = 0xFF5ACF00;// 绿色
//                    } else {
//                        color = 0xFF000000;// 黑色
//                    }
                }
                pixels[x + (y * WIDTH)] = color;
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.RGB_565);
        bitmap.setPixels(pixels, 0, WIDTH, 0, 0, WIDTH, HEIGHT);
        return bitmap;
    }

这样就能生成彩色的二维码了。需要生成其他颜色的修改下面部分即可。(屏蔽部分是四种颜色)

3、结果

添加logo

下面代码可以看出要给二维码图片中间加logo,但是图片只能占据整个二维码图片的小一部分,这里是1/5大小。

1、上传图片

将上面图片拷贝到android目录drawable中(test2就是上图图片)

将android资源文件转换成Bitmap

    MakeQRCodeUtil.gainBitmap(this, R.drawable.test2);

    public static Bitmap gainBitmap(Context context, int drawableId) {
        Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),
                drawableId);
        return bmp;
    }

2、添加logo

传入生成二维码和logo的Bittmp

    //添加logo
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (logo == null) {
            return src;
        }
        // 获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();
        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }
        // logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);
            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }

3、结果

添加背景

1、上传图片

如上logo图片一样转换成Bittmp

2、添加背景

传入生成二维码和背景图的Bittmp(背景图不要小于二维码图)

    /**
     * 给二维码图片加背景
     */
    public static Bitmap addBackground(Bitmap foreground, Bitmap background) {
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        Bitmap newmap = Bitmap
                .createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);
        canvas.drawBitmap(background, 0, 0, null);
        canvas.drawBitmap(foreground, (bgWidth - fgWidth) / 2,
                (bgHeight - fgHeight) * 2 / 5 + 70, null);
        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.restore();
        return newmap;
    }

3、结果

位置就没有调整。可以自己在addBackground方法中调整下。

添加文字

直接添加文字即可

    public static Bitmap addTextToBitmap(Bitmap bmpSrc, String text) {
        int srcWidth = bmpSrc.getWidth();
        int srcHeight = bmpSrc.getHeight();

        // 先计算text所需要的height
        int textSize = 20;
        int padding = 3;
        int textLinePadding = 1;
        // 每行的文字
        int perLineWords = (srcWidth - 2 * padding) / textSize;
        int lineNum = text.length() / perLineWords;
        lineNum = text.length() % perLineWords == 0 ? lineNum : lineNum + 1;
        int textTotalHeight = lineNum * (textSize + textLinePadding) + 2 * padding;

        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight + textTotalHeight,
                Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(Color.WHITE);
            canvas.drawBitmap(bmpSrc, 0, 0, null);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.BLACK);
            paint.setTextSize(textSize);
            String lineText;
            for (int i = 0, startY = srcHeight + textSize, start, end; i < lineNum; i++) {
                start = i * perLineWords;
                end = start + perLineWords;
                lineText = text.substring(start, end > text.length() ? text.length() : end);
                canvas.drawText(lineText, padding, startY, paint);
                startY += textSize + textLinePadding;
            }
            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }
        return bitmap;
    }

结果

添加水印

水印图

代码

    public static Bitmap composeWatermark(Bitmap srcBMP, Bitmap markBMP) {
        if (srcBMP == null) {
            return null;
        }
        // 创建一个新的和SRC长度宽度一样的位图
        Bitmap newb = Bitmap.createBitmap(srcBMP.getWidth(),
                srcBMP.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas cv = new Canvas(newb);
        // 在 0,0坐标开始画入原图
        cv.drawBitmap(srcBMP, 0, 0, null);
        // 在原图的右下角画入水印
        cv.drawBitmap(markBMP, srcBMP.getWidth() - markBMP.getWidth() * 2 / 5,
                srcBMP.getHeight() * 6 / 7, null);
        // 保存
        cv.save(Canvas.ALL_SAVE_FLAG);
        // 存储
        cv.restore();
        return newb;
    }

结果

只有一个头头,为了让你发现它我还特意弄了个箭头,当然正常的水印也不会有这么大。

源码

地址:【源码】二维码生成及美化

结束语

以上就是跟二维码生成以及美化相关接口的总结,希望对你有用。欢迎大家关注我们微信公众号,来交流程序员的技术。如果能留言或者点个赞,我也是很开心的,非常感谢!

å¨è¿éæå¥å¾çæè¿°

参考:

https://blog.csdn.net/u013749540/article/details/65937320

侵删,谢谢

猜你喜欢

转载自blog.csdn.net/twk121109281/article/details/93739594