批量二维码生成

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.1.0</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.1.0</version>
</dependency>
package com.example.demo;

import com.google.zxing.*;
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;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;

/**
 * 二维码工具类
 */
public class QRCodeUtil {
    private static final String CHARSET = "utf-8";
    private static final String FORMAT = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int LOGO_WIDTH = 60;
    // LOGO高度
    private static final int LOGO_HEIGHT = 60;

    private static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);
        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) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (logoPath == null || "".equals(logoPath)) {
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, logoPath, needCompress);
        return image;
    }

    /**
     * 插入LOGO
     *
     * @param source       二维码图片
     * @param logoPath     LOGO图片地址
     * @param needCompress 是否压缩
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
        File file = new File(logoPath);
        if (!file.exists()) {
            throw new Exception("logo file not found.");
        }
        Image src = ImageIO.read(new File(logoPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            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();
            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 logoPath     LOGO地址
     * @param destPath     存放目录
     * @param needCompress 是否压缩LOGO
     * @throws Exception
     */
    public static String encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);
        mkdirs(destPath);
        String fileName = new Random().nextInt(99999999) + "." + FORMAT.toLowerCase();
        ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
        return fileName;
    }

    /**
     * 生成二维码(内嵌LOGO)
     * 调用者指定二维码文件名
     *
     * @param content      内容
     * @param logoPath     LOGO地址
     * @param destPath     存放目录
     * @param fileName     二维码文件名
     * @param needCompress 是否压缩LOGO
     * @throws Exception
     */
    public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);
        mkdirs(destPath);
        fileName = fileName.substring(0, fileName.indexOf(".") > 0 ? fileName.indexOf(".") : fileName.length())
                + "." + FORMAT.toLowerCase();
        ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
        return fileName;
    }

    /**
     * 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.
     * (mkdir如果父目录不存在则会抛出异常)
     *
     * @param destPath 存放目录
     */
    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

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

    /**
     * 生成二维码
     *
     * @param content      内容
     * @param destPath     存储地址
     * @param needCompress 是否压缩LOGO
     * @throws Exception
     */
    public static String encode(String content, String destPath, boolean needCompress) throws Exception {
        return QRCodeUtil.encode(content, null, destPath, needCompress);
    }

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

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

    /**
     * 生成二维码
     *
     * @param content 内容
     * @param output  输出流
     * @throws Exception
     */
    public static void encode(String content, OutputStream output) throws Exception {
        QRCodeUtil.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 (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        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 QRCodeUtil.decode(new File(path));
    }

    public static void main(String[] args) throws Exception {

        //不含Logo
        //QRCodeUtil.encode(text, null, "e:\\", true);
        //含Logo,不指定二维码图片名
        //QRCodeUtil.encode(text, "e:\\csdn.jpg", "e:\\", true);
        //含Logo,指定二维码图片名

        String path = "D:\\qrCode";
        String src = "101010,101011,101012,101013,101014,101015,101016,101017,101018,101019";
        String[] code = src.split(",");
        for (int i = 0; i < code.length; i++) {
            String c = code[i];
            QRCodeUtil.encode(c, path + "//" + c + ".png", path, c, true);
            //createImages(c,new Font("宋体", Font.PLAIN, 30) ,path+"//"+c+".png" );
        }


    }


    private static int[] getWidthAndHeight(String text, Font font) {
        Rectangle2D r = font.getStringBounds(text, new FontRenderContext(
                AffineTransform.getScaleInstance(1, 1), false, false));

        int unitHeight = (int) Math.floor(r.getHeight());//
        // 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
        int width = (int) Math.round(r.getWidth()) + 1;
        // 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
        int height = unitHeight - 5;
        System.out.println("width:" + width + ", height:" + height);
        return new int[]{width, height};
    }

    // 根据str,font的样式以及输出文件目录
    public static void createImages(String text, Font font, String outFile) {
        // 获取font的样式应用在str上的整个矩形
        int[] arr = getWidthAndHeight(text, font);
        int width = 100;
        int height = 100;
        // 创建图片
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_BGR);//创建图片画布
        Graphics g = image.getGraphics();

        g.setColor(Color.WHITE); // 先用白色填充整张图片,也就是背景
        g.fillRect(0, 0, width, height);//画出矩形区域,以便于在矩形区域内写入文字
        g.setColor(Color.black);// 再换成黑色,以便于写入文字
        g.setFont(font);// 设置画笔字体
        g.drawString(text, 0, font.getSize());// 画出一行字符串
        //g.drawString(text, 0, 2 * font.getSize());// 画出第二行字符串,注意y轴坐标需要变动
        g.dispose();
        try {
            ImageIO.write(image, "png", new File(outFile));// 输出png图片
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要在Excel中批量生成二维码9,可以按照以下步骤进行操作: 1. 首先,确保已经安装了可以用于生成二维码的插件或工具,例如二维码生成器。可以在互联网上搜索并下载安装。 2. 打开Excel,并在一个空白单元格中输入第一个需要生成二维码的内容,例如一个链接、文本等。 3. 将这个单元格选中,然后找到插件或工具的功能按钮或选项,选择批量生成二维码的功能。 4. 在批量生成二维码的功能中,设定好生成二维码的数量,这里是9个。 5. 根据插件或工具的操作步骤,选择好二维码生成的样式和尺寸等参数,并确保选择了将二维码添加到Excel的选项。 6. 点击生成按钮或确认按钮,等待插件或工具完成批量生成二维码的操作。 7. 一旦生成完成,就可以在Excel中看到9个二维码按照设定的样式和尺寸添加到了相应的单元格中。 8. 如果需要,可以调整每个二维码所在单元格的大小,以便更好地显示。 通过以上步骤,就可以在Excel中批量生成9个二维码了。如果需要生成其他数量的二维码,只需在第三步中设定相应的参数即可。 ### 回答2: 要批量生成二维码9,可以借助Excel的数据处理和宏功能来实现。以下是生成二维码9的步骤: 1. 准备数据:在Excel中创建一个工作表,将需要生成二维码的数据按照一列一行的方式输入到表格中。 2. 导入插件:下载并安装一个二维码生成插件,常用的有QR Code Generator或Zint Barcode Studio等。 3. 批量生成:在Excel中,创建一个宏(Macro),用于循环遍历每个数据,并调用插件生成对应的二维码。宏的代码可以使用VBA(Visual Basic for Applications)来编写,例如: ```vba Sub GenerateQRCode() Dim rng As Range Dim cell As Range Dim barcode As Object Set rng = Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row) '定义数据范围 For Each cell In rng Set barcode = CreateObject("BARCODE.BarcodeCtrl.1") '创建插件对象 barcode.Code = cell.Value '设置二维码内容 ' 设置二维码生成参数,例如尺寸、颜色等 barcode.Resolution = 300 barcode.BarcodeType = 0 barcode.BackgroundColor = RGB(255, 255, 255) barcode.ForegroundColor = RGB(0, 0, 0) ' 生成二维码图片,并保存 barcode.SaveImage "路径\生成二维码\" & cell.Value & ".png" Set barcode = Nothing '释放资源 Next cell End Sub ``` 在代码中,需要根据插件的具体使用方法进行调整,比如设置二维码尺寸、颜色等参数,并指定生成二维码保存的路径。 4. 运行宏:保存宏并关闭编辑器,回到Excel界面。在工具栏中找到“开发工具”菜单,选择“宏”,然后选择刚才创建的宏(GenerateQRCode),点击运行即可开始批量生成二维码。 以上就是通过Excel批量生成二维码9的方法。注意,使用插件生成二维码需要插件的支持,插件的安装和使用方法可以参考插件的官方文档或使用说明。 ### 回答3: 在Excel中批量生成二维码是可行的。首先,需要安装一个二维码生成器插件,如ZXing插件。然后,需要准备一个包含需生成二维码的内容的Excel表格。 在Excel表格中,可以选择一个列作为二维码生成的基础内容。例如,选中A列,将需要生成二维码的内容填充到A1、A2、A3等单元格中。 接下来,在Excel菜单栏选择“插入”-“插入二维码”。选择插入二维码的位置,弹出插入二维码的对话框。在对话框中,选择需要生成二维码的单元格范围,也就是选择A1、A2、A3等单元格。然后,点击确定生成二维码生成二维码将会自动插入到选中的单元格中。插入的二维码会根据单元格的内容自动更新,这样就可以批量生成多个二维码了。 如果需要批量生成大量的二维码,可以使用Excel的自动填充功能。在A1单元格生成二维码后,选择该单元格,将鼠标移到右下角的小方块上,光标变成十字箭头后,按住鼠标左键向下拖动,Excel会自动填充生成多个二维码生成二维码可以保存为图片,进一步应用到其他文档或打印出来使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值