Java+Swing+ZXing实现文字、图片、链接转二维码工具(微信验证有效、已打包为exe,可永久使用)

发布于:2022-10-29 ⋅ 阅读:(1398) ⋅ 点赞:(1)

Java+Swing+ZXing实现文字、图片、链接转二维码工具

功能介绍

我个人平时也会用到文字、图片、地址等转二维码的情况,但是每次都要找线上网站转,比较麻烦,所以就开发一个可以本地来转二维码的工具,用起来可是真方便。

工具已经打包为exe(所以可永久使用),可以随时在Windows上双击就可运行。

经过对工具的功能测试,在微信上扫描有效。

(说明:这个工具的界面是基于上一个博客的,界面布局可以翻看我上个博客。)

工具测试情况

1.exe介绍
对,exe就长这个样子(很丑对吧,哈哈哈~~)
二维码生成器.exe
打包后的exe大小只有3M左右(具体怎么将java项目打包为exe,不会的话可以私信我,这里就不做过多介绍啦~)
大小
2.运行界面
目前这一版还比较简单(后续会更新图片上传的功能…)
不禁要吐槽吧。。。主页面除了好看外,一无所有,哈哈
主页面
这个二维码类型可以选择子菜单,带logo的二维码和普通二维码

3.文字二维码生成
在这里插入图片描述
生成的文字二维码:
路径
目前在这个路径下
在这里插入图片描述
微信扫描结果:
文字二维码扫描结果
4.图片二维码生成
前面操作都一样,图片的连接放在二维码输入框里
图片二维码
图片二维码:
图片二维码
微信扫描结果:
图片扫描结果
5.链接二维码:
链接二维码
使用百度测试
链接二维码
微信扫描结果:
跳转到百度

代码实现

下面贴上实现的源码
1.前端主页面:MainFrame.java

package com.code2life.frame;

import com.code2life.utils.MusicUtil;
import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;

import javax.swing.*;
import javax.swing.plaf.InsetsUIResource;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.URL;

/**
 * @Author: wen
 * @Date: 2020/9/23 13:06
 * @Description: 主界面
 * @Version: 1.0
 */
public class MainFrame extends JFrame {
    private static MainFrame instance = null;

    private URL imgURL = null;
    private SystemTray sysTray = SystemTray.getSystemTray();
    Image image = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("/images/logo_0.png"));
    private TrayIcon trayicon = new TrayIcon(image, "二维码生成器", createMenu());

    private JPanel jContentPane = null;
    private JLabel jLabel = null;
    private JMenuBar jJMenuBar = null;
    // 二维码类型菜单
    private JMenu jMenu_start = null;

    // 有logo二维码的
    private JMenuItem jMenuItem_logo = null;
    // 无二维码
    private JMenuItem jMenuItem = null;
    // 图片二维码
    private JMenuItem jMenuItemPicture = null;

    private int x, y;

    public MainFrame() {
        super();
        try {
            UIManager.put("RootPane.setupButtonVisible", false);
            org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
            //在一键换肤纯色图后加上这一句
            // BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.translucencyAppleLike;
            //实心的加上后面这一堆。
            BeautyEyeLNFHelper.translucencyAtFrameInactive = false;
            UIManager.put("ToolBar.isPaintPlainBackground", Boolean.FALSE);
            BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.osLookAndFeelDecorated;
            BeautyEyeLNFHelper.launchBeautyEyeLNF();
            //   UIManager.put("RootPane.setupButtonVisible", false);
            UIManager.put("TabbedPane.tabAreaInsets", new InsetsUIResource(0, 0, 0, 0));
            UIManager.put("TabbedPane.contentBorderInsets", new InsetsUIResource(0, 0, 2, 0));
            UIManager.put("TabbedPane.tabInsets", new InsetsUIResource(3, 10, 9, 10));
            Font frameTitleFont = (Font) UIManager.get("InternalFrame.titleFont");
            frameTitleFont = frameTitleFont.deriveFont(Font.PLAIN);
            UIManager.put("InternalFrame.titleFont", frameTitleFont);
        } catch (Exception e) {
            //TODO exception
        }

        initialize();
        new MusicUtil().init();
    }

    public static MainFrame getInstance() {
        if (null == instance) {
            synchronized (MainFrame.class) {
                if (null == instance) {
                    instance = new MainFrame();
                }
            }
        }
        return instance;
    }

    private void initialize() {
        try {
            // 主界面大小
            // this.setSize(800, 533);
            this.setTitle("二维码生成器");
            // 左上角图标
            imgURL = this.getClass().getResource(
                    "/images/logo_0.png");
            this.setIconImage(Toolkit.getDefaultToolkit().getImage(imgURL));

            Toolkit kit = Toolkit.getDefaultToolkit();
            Dimension dimension = kit.getScreenSize();
            this.setExtendedState(JFrame.MAXIMIZED_BOTH);
            this.setBounds(0, 0, dimension.width, dimension.height);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setAlwaysOnTop(false);
            this.setVisible(true);
            this.setResizable(false);

            // 系统关闭事件
            this.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    //初始化托盘图标
                    SystemTrayInitial();
                }
            });

            jMenuItem_logo = new JMenuItem();
            jMenuItem_logo.setText("Logo二维码");

            jMenuItem = new JMenuItem();
            jMenuItem.setText("普通二维码");

            jMenuItemPicture = new JMenuItem();
            jMenuItemPicture.setText("图片二维码");

            jMenu_start = new JMenu();
            jMenu_start.setText("二维码类型");
            jMenu_start.add(jMenuItem_logo);
            jMenu_start.add(jMenuItem);
            jMenu_start.add(jMenuItemPicture);
            // 分割线
            jMenu_start.addSeparator();

            jJMenuBar = new JMenuBar();
            jJMenuBar.setPreferredSize(new Dimension(10, 25));
            jJMenuBar.add(jMenu_start);
            jJMenuBar.setBackground(Color.getHSBColor(192, 220, 243));
            setJMenuBar(jJMenuBar);

            jLabel = new JLabel();
            x = dimension.width;
            y = dimension.height;
            jLabel.setBounds(0, 0, dimension.width, dimension.height);
            imgURL = this.getClass().getResource("/images/main.jpg");
            jLabel.setIcon(new ImageIcon(imgURL));

            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(jLabel, null);
            setContentPane(jContentPane);

            // 菜单点击监听器
            btnListener btn = new btnListener();
            jMenuItem_logo.addActionListener(btn);
            jMenuItem.addActionListener(btn);
            jMenuItemPicture.addActionListener(btn);
            //用来设置窗口随屏幕大小改变
            // sizeWindowOnScreen(this, 0.6, 0.6);
        } catch (Exception e) {
            //TODO exception
        }
    }

    private void sizeWindowOnScreen(MainFrame calculator, double widthRate,
                                    double heightRate) {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        calculator.setSize(new Dimension((int) (screenSize.width * widthRate),
                (int) (screenSize.height * heightRate)));
    }

    /**
     * 退出时初始化系统托盘
     */
    private void SystemTrayInitial() {
        // 判断当前系统是否支持系统栏
        if (!SystemTray.isSupported())
            return;
        try {
            sysTray.add(trayicon);
        } catch (AWTException e1) {
            e1.printStackTrace();
        }
        setVisible(false);
        // 窗体托盘时所显示的消息对话
        trayicon.displayMessage("二维码生成器--By code2life", "二维码生成器", TrayIcon.MessageType.INFO);
        // 击图标时显示窗体
        trayicon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sysTray.remove(trayicon);
                setVisible(true);
            }
        });
    }

    /**
     * 初始化系统托盘右键
     *
     * @return
     */
    private PopupMenu createMenu() {
        // 创建系统栏菜单的方法
        PopupMenu menu = new PopupMenu();
        MenuItem exitItem = new MenuItem("退出生成器");
        // 系统栏退出事件
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        MenuItem openItem = new MenuItem("打开主窗口");
        // 系统栏打开菜单项事件
        openItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (!isVisible()) {
                    setVisible(true);
                    sysTray.remove(trayicon);
                }
            }
        });

        MenuItem viewItem = new MenuItem("您好");
        // 系统栏打开菜单项事件
        viewItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    Runtime.getRuntime().exec("explorer http://axuhongbo.top");
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        });
        menu.add(openItem);
        menu.add(viewItem);
        menu.addSeparator();
        menu.add(exitItem);
        return menu;
    }

    public class btnListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == jMenuItem_logo) {
                QRCodeGeneratorFrame frame = new QRCodeGeneratorFrame(1);
                frame.setVisible(true);
            } else if (e.getSource() == jMenuItem) {
                QRCodeGeneratorFrame frame = new QRCodeGeneratorFrame(0);
                frame.setVisible(true);
            } else if (e.getSource() == jMenuItemPicture) {
                QRCodeGeneratorFrame frame = new QRCodeGeneratorFrame(2);
                frame.setVisible(true);
            }
        }
    }
}

二维码页面布局:QRCodeGeneratorFrame.java

package com.code2life.frame;

import com.code2life.qrcode.QRCodeGenerator;
import com.code2life.utils.FileUtil;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: wen
 * @Date: 2020/9/23 15:42
 * @Description: 二维码生成布局
 * @Version: 1.0
 */
public class QRCodeGeneratorFrame extends JDialog {

    private JLabel jLabel1 = null;
    private JLabel jLabel2 = null;

    // 二维码名称
    private JTextField jTextFieldName = null;
    // 二维码内容
    private JTextField jTextFieldContent = null;

    // 二维码Logo选择器
    private JFileChooser jFileChooserLogo = null;
    // 二维码Logo选择按钮
    private JButton jButtonChoose = null;
    // 二维码Logo链接地址
    private JTextField jTextFieldLogo = null;

    // 二维码生成按钮
    private JButton jButtonOk = null;
    // 二维码生成器面板
    private JPanel jContentPane = null;

    // 二维码图片内容选择器
    private JFileChooser jFileChooserContent = null;
    // 二维码图片内容选择按钮
    private JButton jButtonContentChoose = null;

    private int type = 0;

    /**
     * @param type 二维码类型 0-普通二维码 1-logo二维码 2-内容为图片的二维码
     */
    public QRCodeGeneratorFrame(int type) {
        super();
        this.type = type;
        initialize();
        // 给提交按钮绑定监听器
        jButtonOk.addActionListener(new btnListener());
        if (1 == type) {
            jButtonChoose.addActionListener(new btnListener());
        } else if (2 == type) {
            jButtonChoose.addActionListener(new btnListener());
            jButtonContentChoose.addActionListener(new btnListener());
        }
        this.setModal(true);

    }

    private void initialize() {
        this.setSize(580, 278);
        this.setModal(true);
        this.setLocationRelativeTo(null);
        this.setTitle("二维码生成");

        jContentPane = new JPanel();
        jContentPane.setLayout(null);

        jTextFieldName = new JTextField();
        jTextFieldName.setBounds(new Rectangle(100, 33, 125, 24));

        jLabel1 = new JLabel();
        jLabel1.setBounds(new Rectangle(20, 33, 100, 24));
        jLabel1.setText("二维码名称:");
        jLabel1.setFont(new Font("粗体", Font.BOLD, 12));
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        jLabel2 = new JLabel();
        // 区分二维码内容为图片还是其他
        if (2 == type) {
            jLabel2.setText("二维码图片:");
            jLabel2.setBounds(new Rectangle(245, 33, 80, 24));
            jLabel2.setFont(new Font("粗体", Font.BOLD, 12));
            this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

            jTextFieldContent = new JTextField();
            jTextFieldContent.setBounds(new Rectangle(325, 33, 165, 24));
            jButtonContentChoose = new JButton();
            jButtonContentChoose.setBounds(new Rectangle(485, 33, 65, 24));
            jButtonContentChoose.setFont(new Font("粗体", Font.BOLD, 12));
            jButtonContentChoose.setText("选择");

            jTextFieldContent = new JTextField();
            jTextFieldContent.setBounds(new Rectangle(339, 33, 125, 24));

            jContentPane.add(jTextFieldContent, null);
            jContentPane.add(jButtonContentChoose, null);
            jContentPane.add(jLabel2, null);
        } else {
            jLabel2.setText("二维码内容:");
            jLabel2.setBounds(new Rectangle(279, 33, 100, 24));
            jLabel2.setFont(new Font("粗体", Font.BOLD, 12));
            this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

            jTextFieldContent = new JTextField();
            jTextFieldContent.setBounds(new Rectangle(359, 33, 185, 24));

            jContentPane.add(jTextFieldContent, null);
            jContentPane.add(jLabel2, null);
        }
        // 区分二维码是否带Logo
        if (1 == type || 2 == type) {
            jTextFieldLogo = new JTextField();
            jTextFieldLogo.setBounds(new Rectangle(20, 92, 205, 24));

            jButtonChoose = new JButton();
            jButtonChoose.setBounds(new Rectangle(240, 92, 85, 24));
            jButtonChoose.setFont(new Font("粗体", Font.BOLD, 12));
            jButtonChoose.setText("Logo选择");

            jContentPane.add(jTextFieldLogo, null);
            jContentPane.add(jButtonChoose, null);

            jButtonOk = new JButton();
            jButtonOk.setBounds(new Rectangle(250, 145, 92, 26));
            jButtonOk.setText("开始生成");
            jButtonOk.setFont(new Font("粗体", Font.BOLD, 12));
            jButtonOk.setForeground(Color.blue);

        } else if (0 == type || 2 == type) {
            jButtonOk = new JButton();
            jButtonOk.setBounds(new Rectangle(250, 130, 92, 26));
            jButtonOk.setText("开始生成");
            jButtonOk.setFont(new Font("粗体", Font.BOLD, 12));
            jButtonOk.setForeground(Color.blue);

        }

        jContentPane.add(jButtonOk, null);
        jContentPane.add(jLabel1, null);
        jContentPane.add(jTextFieldName, null);
        this.setContentPane(jContentPane);
    }

    public class btnListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            try {
                // 二维码生成提交
                if (event.getSource() == jButtonOk) {
                    // 二维码名称
                    String name = jTextFieldName.getText();
                    // 二维码上没有显示内容则传递空的list集合即可
                    List<String> showContent = new ArrayList<>();
                    showContent.add(name);
                    String content = jTextFieldContent.getText();
                    if (content == null || "".equals(content)) {
                        if (2 == type) {
                            JOptionPane.showMessageDialog(null, "请选择二维码图片");
                            return;
                        } else {
                            JOptionPane.showMessageDialog(null, "请输入二维码内容");
                            return;
                        }
                    }else {
                        if (1 == type) {
                            // 有logo的二维码
                            File file = jFileChooserLogo.getSelectedFile();
                            if (file !=null) {
                                String filePath = file.getAbsolutePath();
                                String path = new QRCodeGenerator().encode(showContent, content, filePath, true, new FileUtil());
                                System.out.println("有logo的二维码  " + path);
                                JOptionPane.showMessageDialog(null, "生成成功,本地地址 :" + path, "生成结果提醒",
                                        JOptionPane.INFORMATION_MESSAGE);
                            } else {
                                JOptionPane.showMessageDialog(null, "Logo不能为空");
                                return;
                            }
                        } else if (2 ==type) {
                            // 判断是否有logo
                            File logoFile = jFileChooserLogo.getSelectedFile();
                            String logoPath = "";
                            if (logoFile !=null) {
                                logoPath = logoFile.getAbsolutePath();
                            }
                            File pictureFile = jFileChooserContent.getSelectedFile();
                            if (pictureFile !=null) {
                                String filePath = pictureFile.getAbsolutePath();
                                // 需要根据图片地址将图片内容转码,然后上传到资源服务器,将所在服务器的地址放入二维码中即可(目前先写一个默认的)
                                String routePath = "https://thirdwx.qlogo.cn/mmopen/vi_32/icniaGmw8xibozWwpo3fNBLsgDZouEU7VrcNZdTJIDAOpREvgQRWpC7Tye2ZfNQVwUgaGNhGCHqSVyTmDP43e5zfw/0";
                                System.out.println("图片二维码资源地址  " + routePath);
                                String path = "";
                                if (logoPath!=null && !"".equals(logoPath)) {
                                    path = new QRCodeGenerator().encode(showContent, routePath, logoPath, true, new FileUtil());
                                } else {
                                    path = new QRCodeGenerator().encode(showContent, routePath, new FileUtil());
                                }
                                JOptionPane.showMessageDialog(null, "生成成功,本地地址 :" + path, "生成结果提醒",
                                        JOptionPane.INFORMATION_MESSAGE);
                            } else {
                                JOptionPane.showMessageDialog(null, "二维码图片不能为空");
                                return;
                            }
                        } else {
                            // 无logo的二维码
                            String path = new QRCodeGenerator().encode(showContent, content, new FileUtil());
                            System.out.println("无logo的二维码  " + path);
                            JOptionPane.showMessageDialog(null, "生成成功,本地地址 :" + path, "生成结果提醒",
                                    JOptionPane.INFORMATION_MESSAGE);
                        }
                    }
                } else if (event.getSource() == jButtonChoose) {
                    // Logo选择
                    jFileChooserLogo = new JFileChooser();
                    jFileChooserLogo.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg", "png");
                    jFileChooserLogo.setFileFilter(filter);
                    jFileChooserLogo.showDialog(new JLabel(), "选择");
                    File file = jFileChooserLogo.getSelectedFile();
                    if (file != null) {
                        if (file.isDirectory()) {
                            System.out.println("文件夹:" + file.getAbsolutePath());
                        } else if (file.isFile()) {
                            System.out.println("文件:" + file.getAbsolutePath());
                            jTextFieldLogo.setText(file.getAbsolutePath());
                        }
                    }
                    System.out.println(jFileChooserLogo.getSelectedFile().getName());
                } else if (event.getSource() == jButtonContentChoose) {
                    // 二维码图片选择
                    FileFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg", "png");
                    jFileChooserContent = new JFileChooser();
                    jFileChooserContent.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    jFileChooserContent.showDialog(new JLabel(), "选择");
                    jFileChooserContent.setFileFilter(filter);
                    File file = jFileChooserContent.getSelectedFile();
                    if (file != null) {
                        if (file.isDirectory()) {
                            System.out.println("二维码图片文件夹:" + file.getAbsolutePath());
                        } else if (file.isFile()) {
                            System.out.println("二维码图片文件:" + file.getAbsolutePath());
                            jTextFieldContent.setText(file.getAbsolutePath());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

2.转二维码代码实现:QRCodeGenerator.java

package com.code2life.qrcode;

import com.code2life.utils.FileUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

/**
 * @Author: wen
 * @Date: 2020/9/23 10:52
 * @Description: 自定义二维码生成器
 * @Version: 1.0
 */
public class QRCodeGenerator {

    private static final String CHARSET = "utf-8";

    // 二维码尺寸

    private static final int QRCODE_SIZE = 300;

    // LOGO宽度

    private static final int WIDTH = 60;

    // LOGO高度

    private static final int HEIGHT = 60;

    private static BufferedImage createImage(List<String> code, String content, String imgPath, boolean needCompress) throws Exception {
        Map<EncodeHintType, Object> hints = new Hashtable<>();
        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);
            }

        }

        //在二维码下方增加文字显示
        BufferedImage bi = new BufferedImage(width, height + 20 * code.size(), BufferedImage.TYPE_INT_RGB);//将高度增加20,在二维码下方增加一个区域显示文字
        Graphics2D g2 = bi.createGraphics();
        g2.setBackground(new Color(0xFF, 0xFF, 0xFF));
        g2.clearRect(0, 0, width, height);
        g2.drawImage(image, 0, 20 * code.size(), width, height, null); //x,y为image图片的位置
        //设置生成图片的文字样式
        Font font = new Font("黑体", Font.BOLD, 17);
        g2.setFont(font);
        g2.setPaint(new Color(0x0, 0x0, 0x0));
        // 设置字体在图片中的位置 在这里是居中
        for (int i = 0; i < code.size(); ) {
            // 防止生成的文字带有锯齿
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            // 在图片上生成文字
            g2.drawString(code.get(i), 5, 20 * ++i); //x,y为文字的位置
        }
        image = bi;
        if (imgPath == null || "".equals(imgPath))
            return image;
        // 插入图片
        QRCodeGenerator.insertImage(image, imgPath, needCompress, code);
        return image;

    }

    /**
     * 插入logo图标
     *
     * @param source       二维码Image对象
     * @param imgPath      logo路径
     * @param needCompress 是否需要缩小logo图标
     * @param code
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress, List<String> code) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
            g.drawImage(src, 0, 0, width, height, null); // 绘制图
            // 画边框
            g.setColor(Color.BLACK);
            g.drawRect(4, 4, width - 8, height - 8);
            g.drawRect(5, 5, width - 10, height - 10);
            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 + code.size() * 20, width, height, null);//logo的位置可能需要调整
        Shape shape = new RoundRectangle2D.Float(x, y + code.size() * 20, width, width, 6, 6);//阴影的位置可能需要调整
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();

    }


    /**
     * 生成包含logo的二维码
     *
     * @param code         需要显示在二维码上方的list文字集合
     * @param content      二维码中包含的内容
     * @param imgPath      logo图像地址
     * @param needCompress 是否需要缩小logo图标
     * @param fileUtil     保存文件的类对象
     * @return 保存后的文件路径
     * @throws Exception
     */

    public static String encode(List<String> code, String content, String imgPath, boolean needCompress, FileUtil fileUtil) throws Exception {

        BufferedImage image = QRCodeGenerator.createImage(code, content, imgPath, needCompress);
        //获取当前时间并格式化
        String path = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new Date());
        path = path.substring(0, 10);
        //保存文件到磁盘
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        return fileUtil.writeFile(input, "D:/qrcode/" + path, path + ".png");
    }

    /**
     * 不包含logo的二维码
     * @param code     需要显示在二维码上方的list字符串集合
     * @param content  二维码中的内容
     * @param fileUtil 保存文件的工具类
     * @return 保存成功之后的路径地址
     * @throws Exception
     */
    public static String encode(List<String> code, String content, FileUtil fileUtil) throws Exception {
        return QRCodeGenerator.encode(code, content, null, false, fileUtil);
    }

}

基本上就这些代码,后续会更新一些新的功能,比如上传图片、文本上传等等…

写在最后

想要尝试试下该工具,可联系博主获取二维码生成器的.exe包或者完整的源码,博主威:(Code2Life2)
感谢阅读,觉得好的话,可以关注、点赞、转发三连哈。你的支持就是我最大的动力!!!(后续功能更新,请持续关注我的博客,同时还会开发一些其他工具,有什么好想法可以和我交流哈)

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到