Java通过谷歌zxing生成二维码可添加logo图片

package com.example.demo.test;

import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.util.*;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCodeUtils {

    // 二维码背景色
    private static final int BLACK = 0xFF000000;
    // 二维码颜色
    private static final int WHITE = 0xFFFFFFFF;
    // 二维码尺寸大小
    private static final int QRCODE_SIZE = 300;
    // 二维码中间LOGO宽度
    private static final int LOGO_WIDTH = 60;
    // 二维码中间LOGO高度
    private static final int LOGO_HEIGHT = 60;
    // 二维码base64编辑集
    private static final String CHARSET = "UTF-8";
    // 二维码图片格式
    private static final String FORMAT_NAME = "JPG";


    /**
     * 强制去除二维码白边
     * 先根据内容生成二维码,再根据预设的大小进行缩放,预设的大小 - 缩放后的大小 = 白边大小
     * 白边的生成与二维码的内容多少(内容越多,生成的二维码越密集)以及设置的大小有关
     * 因为在生成二维码之后,才将白边裁掉,所以裁剪之后的二维码大小与预设的大小将不一致
     * @param matrix
     * @return
     */
    private static BitMatrix deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1])){
                    resMatrix.set(i, j);
                }
            }
        }
        return resMatrix;
    }

    /**
     *  设置QR二维码参数
     * @return
     */
    private static Map<EncodeHintType, Object> getDecodeHintType() {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<>(3);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        return hints;
    }

    /**
     * 生成二维码
     * @param content 扫描内容
     * @param logoImgPath LOGO图片地址
     * @param needCompress 是否压缩
     * @return 二维码图片
     * @throws Exception
     */
    private static BufferedImage createImage(String content,String logoImgPath,boolean needCompress) throws Exception {
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, QRCodeUtils.getDecodeHintType());
        //强制去除白边
        //bitMatrix = deleteWhite(bitMatrix);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }
        if (null == logoImgPath || "".equals(logoImgPath)) {
            return image;
        }
        // 插入LOGO图片
        QRCodeUtils.insertImage(image,logoImgPath,needCompress);
        return image;
    }

    /**
     * 插入LOGO
     * @param source 二维码图片
     * @param logoImgPath LOGO图片地址
     * @param needCompress 是否压缩
     * @throws Exception
     */
    private static void insertImage(BufferedImage source,String logoImgPath,boolean needCompress) throws Exception {
        File file = new File(logoImgPath);
        if (!file.exists()) {
            System.err.println(logoImgPath + "该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(logoImgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        // 压缩LOGO
        if (needCompress) {
            if (width > LOGO_WIDTH) {
                width = LOGO_WIDTH;
            }
            if (height > LOGO_HEIGHT) {
                height = LOGO_HEIGHT;
            }
            Image image = src.getScaledInstance(width, height,Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            // 绘制缩小后的LOGO图
            g.drawImage(image,0,0,null);
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成二维码(内嵌LOGO)
     *
     * @param content 扫描内容
     * @param logoImgPath LOGO图片地址
     * @param destPath 存放目录
     * @param needCompress 是否压缩LOGO
     * @throws Exception
     */
    public static String encode(String content,String logoImgPath, String destPath,boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtils.createImage(content,logoImgPath,needCompress);
        File file =new File(destPath);
        //当文件夹不存在时,自动创建文件夹
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        ImageIO.setCacheDirectory(file);
        String fileName = System.currentTimeMillis() + ".jpg";
        ImageIO.write(image,FORMAT_NAME,new File(destPath + File.separator + fileName));
        return fileName;
    }

    /**
     * 生成二维码
     * @param content 扫描内容
     * @param destPath 存储地址
     * @throws Exception
     */
    public static String encode(String content,String destPath) throws Exception {
        return QRCodeUtils.encode(content,null, destPath, false);
    }

    /**
     * 生成二维码(内嵌LOGO,无需压缩logo图片)
     * @param content 扫描内容
     * @param logoImgPath LOGO图片地址
     * @param destPath 存储地址
     * @throws Exception
     */
    public static String encode(String content, String logoImgPath, String destPath) throws Exception {
        return QRCodeUtils.encode(content, logoImgPath, destPath, false);
    }


    /**
     * 生成二维码(内嵌LOGO)
     * @param content 扫描内容
     * @param logoImgPath LOGO图片地址
     * @param output 输出流
     * @param needCompress 是否压缩LOGO
     * @throws Exception
     */
    public static void encode(String content,String logoImgPath,OutputStream output,boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtils.createImage(content,logoImgPath,needCompress);
        ImageIO.write(image,FORMAT_NAME, output);
    }

    /**
     * 生成二维码
     * @param content 扫描内容
     * @param output 输出流
     * @throws Exception
     */
    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtils.encode(content, null, output, false);
    }

    /**
     * 解析二维码
     * @param file 二维码图片
     * @return
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (Objects.isNull(image)) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<>(1);
        hints.put(DecodeHintType.CHARACTER_SET,CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    /**
     * 解析二维码
     * @param path 二维码图片地址
     * @return
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        return QRCodeUtils.decode(new File(path));
    }

    public static void main(String[] args) throws Exception {
        String text = "http://www.baidu.com";
        String logoPath = "D:\\test\\test.jpg";
        String destPath = "D:\\test";
        System.out.println(QRCodeUtils.encode(text, logoPath, destPath, true));
        //System.out.println(QRCodeUtils.decode("D:\\test\\1648114245726.jpg"));
    }
}  

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用zxing提供的MultiFormatWriter类来生成二维码。要在二维码上方生成可换行标题,可以使用Bitmap.createBitmap()方法创建一个新的Bitmap对象,并在上面绘制标题和二维码。具体代码如下: ```java import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class QRCodeUtil { /** * 生成有标题的二维码 * * @param content 二维码内容 * @param title 标题 * @param width 二维码宽度 * @param height 二维码高度 * @return 有标题的二维码Bitmap对象 */ public static Bitmap createQRCodeWithTitle(String content, String title, int width, int height) { try { // 生成二维码矩阵 BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height); // 获取二维码图片的宽高 int qrCodeWidth = bitMatrix.getWidth(); int qrCodeHeight = bitMatrix.getHeight(); // 新建一个Bitmap对象 Bitmap bitmap = Bitmap.createBitmap(qrCodeWidth, qrCodeHeight + 50, Bitmap.Config.ARGB_8888); // 在Bitmap上绘制标题和二维码 Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setTextSize(30); paint.setColor(0xff000000); Rect bounds = new Rect(); paint.getTextBounds(title, 0, title.length(), bounds); int titleHeight = bounds.height(); canvas.drawText(title, (qrCodeWidth - bounds.width()) / 2f, titleHeight, paint); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix qrCodeMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeWidth, qrCodeHeight); int[] qrCodePixels = new int[qrCodeWidth * qrCodeHeight]; for (int y = 0; y < qrCodeHeight; y++) { int offset = y * qrCodeWidth; for (int x = 0; x < qrCodeWidth; x++) { qrCodePixels[offset + x] = bitMatrix.get(x, y) ? 0xff000000 : 0xffffffff; } } bitmap.setPixels(qrCodePixels, 0, qrCodeWidth, 0, titleHeight + 10, qrCodeWidth, qrCodeHeight); return bitmap; } catch (WriterException e) { e.printStackTrace(); return null; } } } ``` 调用方式: ```java Bitmap bitmap = QRCodeUtil.createQRCodeWithTitle("二维码内容", "标题\n换行", 400, 400); imageView.setImageBitmap(bitmap); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值