/*
* Created by JFormDesigner on Wed Aug 26 13:36:16 CST 2020
*/
package qr;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* @author 1
*/
public class CodeTest extends JFrame {
public static void main(String[] args) {
new CodeTest().setVisible(true);
}
public CodeTest() {
initComponents();
setTitle("二维码"); // 标题
setResizable(false); // 固定窗体
//setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); //退出窗口不适用
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口 ,退出进程
//显示屏幕中央
int width = 720; //宽度
int height = 535; // 高度
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
/** 屏幕宽度 */
int screenWidth = screenSize.width;
/** 屏幕高度 */
int screenHeight = screenSize.height;
setLocation((screenWidth - width) / 2, (screenHeight - height) / 2);
setMinimumSize(new Dimension(width,height)); //窗体大小
radioButton1.setSelected(true);
textField1.setText("1");
textField2.setEditable(false);
textField3.setEditable(false);
//二维码
radioButton1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
radioButton1.setSelected(true);
radioButton2.setSelected(false);
button3.setEnabled(true);
}
});
//条形码
radioButton2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
radioButton1.setSelected(false);
radioButton2.setSelected(true);
button3.setEnabled(false);
textArea1.setText("");
textField2.setText("");
textField3.setText("");
label5.setIcon(new ImageIcon());
}
});
//生成二维码按钮
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//二维码
if(radioButton1.isSelected()){
//内容
String conext = textArea1.getText();
//数量
String countNum = textField1.getText();
if(countNum == null || "".equals(countNum)){
JOptionPane.showMessageDialog(null,"数量不能为空");
return;
}
//保存路径
String path = textField2.getText();
if(path == null || "".equals(path)){
JOptionPane.showMessageDialog(null,"保存路径不能为空");
return;
}
//图片路径
String imgPath = textField3.getText();
int count = Integer.valueOf(countNum);
for(int i=0; i<count ; i++){
try {
QRCode.encode(conext, imgPath, path, true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
JOptionPane.showMessageDialog(null,"生成完成");
}
//条形码
if(radioButton2.isSelected()){
String context = textArea1.getText();
if (context.length() > 100){
JOptionPane.showMessageDialog(null,"内容长度超过100个字符");
return ;
}
//数量
String countNum = textField1.getText();
if(countNum == null || "".equals(countNum)){
JOptionPane.showMessageDialog(null,"数量不能为空");
return;
}
//保存路径
String path = textField2.getText();
if(path == null || "".equals(path)){
JOptionPane.showMessageDialog(null,"保存路径不能为空");
return;
}
int count = Integer.valueOf(countNum);
for(int i=0; i<count ; i++){
try {
BufferedImage image = GoogleBarCodeUtils.insertWords(
GoogleBarCodeUtils.getBarCode(context), context);
String file = new Random().nextInt(99999999)+".jpg";
ImageIO.write(image, "jpg", new File(path +"/"+file));
} catch (Exception ex) {
ex.printStackTrace();
}
}
JOptionPane.showMessageDialog(null,"生成完成");
}
}
});
//保存路径
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Runnable runnable = new Runnable() {
@Override
public void run() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int option = fileChooser.showOpenDialog(getContentPane());
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
textField2.setText(file.getPath());
//System.out.println("选择文件或目录: " + file.getPath());
}
}
};
SwingUtilities.invokeLater(runnable);
}
});
//选择文件路径
button3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Runnable runnable = new Runnable() {
@Override
public void run() {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter ("Some Images", "jpg", "gif", "png", "jpeg");
fileChooser.setFileFilter(filter);
int option = fileChooser.showOpenDialog(getContentPane());
if (option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
String path = file.getPath();
textField3.setText(path);
Icon icon = null;
try {
icon = new ImageIcon(new URL("file:///"+ path));
//icon = new ImageIcon(new URL("https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg"));
} catch (MalformedURLException e) {
e.printStackTrace();
}
label5.setIcon(icon);
}
}
};
SwingUtilities.invokeLater(runnable);
}
});
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
panel1 = new JPanel();
radioButton1 = new JRadioButton();
radioButton2 = new JRadioButton();
label1 = new JLabel();
label2 = new JLabel();
textField1 = new JTextField();
label3 = new JLabel();
textField2 = new JTextField();
button2 = new JButton();
label4 = new JLabel();
textField3 = new JTextField();
button3 = new JButton();
panel2 = new JPanel();
label5 = new JLabel();
panel3 = new JPanel();
scrollPane1 = new JScrollPane();
textArea1 = new JTextArea();
button1 = new JButton();
//======== this ========
Container contentPane = getContentPane();
contentPane.setLayout(null);
//======== panel1 ========
{
panel1.setBorder(new TitledBorder("\u751f\u6210\u914d\u7f6e"));
panel1.setLayout(null);
//---- radioButton1 ----
radioButton1.setText("\u4e8c\u7ef4\u7801");
panel1.add(radioButton1);
radioButton1.setBounds(150, 35, 80, 25);
//---- radioButton2 ----
radioButton2.setText("\u6761\u5f62\u7801");
panel1.add(radioButton2);
radioButton2.setBounds(235, 35, 100, 25);
//---- label1 ----
label1.setText("\u7c7b\u578b\uff1a");
panel1.add(label1);
label1.setBounds(new Rectangle(new Point(95, 40), label1.getPreferredSize()));
//---- label2 ----
label2.setText("\u6570\u91cf\uff1a");
panel1.add(label2);
label2.setBounds(95, 80, 45, 20);
panel1.add(textField1);
textField1.setBounds(150, 75, 180, 25);
//---- label3 ----
label3.setText("\u4fdd\u5b58\u8def\u5f84\uff1a");
panel1.add(label3);
label3.setBounds(70, 120, 85, 20);
panel1.add(textField2);
textField2.setBounds(150, 115, 380, 25);
//---- button2 ----
button2.setText("\u9009\u62e9");
panel1.add(button2);
button2.setBounds(565, 115, 100, button2.getPreferredSize().height);
//---- label4 ----
label4.setText("\u4e8c\u7ef4\u7801Logo\uff1a");
panel1.add(label4);
label4.setBounds(55, 160, 85, 25);
panel1.add(textField3);
textField3.setBounds(150, 160, 380, 25);
//---- button3 ----
button3.setText("\u9009\u62e9Logo");
panel1.add(button3);
button3.setBounds(565, 160, 100, 24);
//======== panel2 ========
{
panel2.setBorder(new TitledBorder("\u56fe\u7247"));
panel2.setLayout(null);
panel2.add(label5);
label5.setBounds(30, 25, 140, 100);
{
// compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < panel2.getComponentCount(); i++) {
Rectangle bounds = panel2.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = panel2.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
panel2.setMinimumSize(preferredSize);
panel2.setPreferredSize(preferredSize);
}
}
panel1.add(panel2);
panel2.setBounds(150, 190, 200, 140);
{
// compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < panel1.getComponentCount(); i++) {
Rectangle bounds = panel1.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = panel1.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
panel1.setMinimumSize(preferredSize);
panel1.setPreferredSize(preferredSize);
}
}
contentPane.add(panel1);
panel1.setBounds(10, 160, 695, 340);
//======== panel3 ========
{
panel3.setBorder(new TitledBorder("\u5185\u5bb9"));
panel3.setLayout(null);
//======== scrollPane1 ========
{
scrollPane1.setViewportView(textArea1);
}
panel3.add(scrollPane1);
scrollPane1.setBounds(30, 25, 505, 110);
{
// compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < panel3.getComponentCount(); i++) {
Rectangle bounds = panel3.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = panel3.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
panel3.setMinimumSize(preferredSize);
panel3.setPreferredSize(preferredSize);
}
}
contentPane.add(panel3);
panel3.setBounds(10, 10, 565, 150);
//---- button1 ----
button1.setText("\u751f\u6210");
contentPane.add(button1);
button1.setBounds(600, 65, 85, button1.getPreferredSize().height);
{
// compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < contentPane.getComponentCount(); i++) {
Rectangle bounds = contentPane.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = contentPane.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
contentPane.setMinimumSize(preferredSize);
contentPane.setPreferredSize(preferredSize);
}
pack();
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
private JPanel panel1;
private JRadioButton radioButton1;
private JRadioButton radioButton2;
private JLabel label1;
private JLabel label2;
private JTextField textField1;
private JLabel label3;
private JTextField textField2;
private JButton button2;
private JLabel label4;
private JTextField textField3;
private JButton button3;
private JPanel panel2;
private JLabel label5;
private JPanel panel3;
private JScrollPane scrollPane1;
private JTextArea textArea1;
private JButton button1;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
package qr;
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;
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 QRCode {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
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(String content, String imgPath,
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 (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCode.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source
* 二维码图片
* @param imgPath
* LOGO图片地址
* @param needCompress
* 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) 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;
}
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 imgPath
* LOGO地址
* @param destPath
* 存放目录
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String imgPath, String destPath,
boolean needCompress) throws Exception {
BufferedImage image = QRCode.createImage(content, imgPath,
needCompress);
mkdirs(destPath);
String file = new Random().nextInt(99999999)+".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
return file;
}
/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
* @date 2013-12-11 上午10:16:36
* @param destPath 存放目录
*/
public static void mkdirs(String destPath) {
File file =new File(destPath);
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath)
throws Exception {
QRCode.encode(content, imgPath, destPath, false);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String destPath,
boolean needCompress) throws Exception {
QRCode.encode(content, null, destPath, needCompress);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String destPath) throws Exception {
QRCode.encode(content, null, destPath, false);
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param output
* 输出流
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String imgPath,
OutputStream output, boolean needCompress) throws Exception {
BufferedImage image = QRCode.createImage(content, imgPath,
needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param output
* 输出流
* @throws Exception
*/
public static void encode(String content, OutputStream output)
throws Exception {
QRCode.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 QRCode.decode(new File(path));
}
public static void main(String[] args) throws Exception {
String text = "http://www.baidu.com"; //这里设置自定义网站url
String logoPath = "C:\\15.jpg";
String destPath = "C:\\";
System.out.println(QRCode.encode(text, logoPath, destPath, true));
}
}
package qr;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
*
* @Auther: ljt
* @Version 1.0
* @Date: 2020/08/26/16:14
* @Description:
*/
public class GoogleBarCodeUtils {
/** 条形码宽度 */
private static final int WIDTH = 300;
/** 条形码高度 */
private static final int HEIGHT = 50;
/** 加文字 条形码 */
private static final int WORDHEIGHT = 75;
/**
* 设置 条形码参数
*/
private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
private static final long serialVersionUID = 1L;
{
// 设置编码方式
put(EncodeHintType.CHARACTER_SET, "utf-8");
}
};
/**
* 生成 图片缓冲
* @author fxbin
* @param vaNumber VA 码
* @return 返回BufferedImage
*/
public static BufferedImage getBarCode(String vaNumber){
try {
Code128Writer writer = new Code128Writer();
// 编码内容, 编码类型, 宽度, 高度, 设置参数
BitMatrix bitMatrix = writer.encode(vaNumber, BarcodeFormat.CODE_128, WIDTH, HEIGHT, hints);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
/**
* 把带logo的二维码下面加上文字
* @author fxbin
* @param image 条形码图片
* @param words 文字
* @return 返回BufferedImage
*/
public static BufferedImage insertWords(BufferedImage image, String words){
// 新的图片,把带logo的二维码下面加上文字
if (words != null && !"".equals(words)) {
BufferedImage outImage = new BufferedImage(WIDTH, WORDHEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = outImage.createGraphics();
// 抗锯齿
setGraphics2D(g2d);
// 设置白色
setColorWhite(g2d);
// 画条形码到新的面板
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
// 画文字到新的面板
Color color=new Color(0, 0, 0);
g2d.setColor(color);
// 字体、字型、字号
g2d.setFont(new Font("微软雅黑", Font.PLAIN, 18));
//文字长度
int strWidth = g2d.getFontMetrics().stringWidth(words);
//总长度减去文字长度的一半 (居中显示)
int wordStartX=(WIDTH - strWidth) / 2;
//height + (outImage.getHeight() - height) / 2 + 12
int wordStartY=HEIGHT+20;
// 画文字
g2d.drawString(words, wordStartX, wordStartY);
g2d.dispose();
outImage.flush();
return outImage;
}
return null;
}
/**
* 设置 Graphics2D 属性 (抗锯齿)
* @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
*/
private static void setGraphics2D(Graphics2D g2d){
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
g2d.setStroke(s);
}
/**
* 设置背景为白色
* @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
*/
private static void setColorWhite(Graphics2D g2d){
g2d.setColor(Color.WHITE);
//填充整个屏幕
g2d.fillRect(0,0,600,600);
//设置笔刷
g2d.setColor(Color.BLACK);
}
public static void main(String[] args) throws IOException {
// BufferedImage image = insertWords(getBarCode("123456789"), "123456789");
// A80/90R8A(8A侧通孔)
BufferedImage image = insertWords(getBarCode("1 23 4567890 12 "), "1 23 4567890 12 ");
ImageIO.write(image, "jpg", new File("C:\\Users\\pax\\Documents\\aaaaaaaaaaa\\barcode.png"));
}
}