【Java】生成二维码之Java实现

来源:互联网 发布:淘宝上怎么发布宝贝 编辑:程序博客网 时间:2024/06/16 13:16

二维码生成

核心代码

二维码的特点:
1.高密度编码,信息容量大:可容纳多达1850个大写字母或2710个数字或1108个字节,或500多个汉字,比普通条码信息容量约高几十倍。
2.编码范围广:该条码可以把图片、声音、文字、签字、指纹等可以数字化的信息进行编码,用条码表示出来;可以表示多种语言文字;可表示图像数据。

示例如下:

import com.google.zxing.common.BitMatrix;import javax.imageio.ImageIO;import java.io.File;import java.io.OutputStream;import java.io.IOException;import java.awt.image.BufferedImage;//核心代码public final class MatrixToImageWriter {    private static final int BLACK = 0xFF000000;    private static final int WHITE = 0xFFFFFFFF;    private MatrixToImageWriter() {    }    public static BufferedImage toBufferedImage(BitMatrix matrix) {        int width = matrix.getWidth();        int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);            }        }        return image;    }    public static void writeToFile(BitMatrix matrix, String format, File file)            throws IOException {        BufferedImage image = toBufferedImage(matrix);        if (!ImageIO.write(image, format, file)) {            throw new IOException("Could not write an image of format "                    + format + " to " + file);        }    }    public static void writeToStream(BitMatrix matrix, String format,            OutputStream stream) throws IOException {        BufferedImage image = toBufferedImage(matrix);        if (!ImageIO.write(image, format, stream)) {            throw new IOException("Could not write an image of format "                    + format);        }    }}

数据库连接

根据需求是否用到数据库:

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;public class DB {    public static void main(String[] args) {        System.out.println(DB.getConnection());    }    public static Connection getConnection(){        Connection conn = null;        String driver = "com.mysql.jdbc.Driver";        String url = "jdbc:mysql://localhost:3306/elevator?user=root&password=1908366654&characterEncoding=UTF-8&mysqlEncoding=UTF-8";        try {            Class.forName(driver);            conn = DriverManager.getConnection(url);        } catch (ClassNotFoundException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return conn;    }    public static PreparedStatement createPST(Connection conn, String sql) {        PreparedStatement PST = null;        try {            PST = conn.prepareStatement(sql);        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return PST;    }    public static ResultSet getRs(PreparedStatement PST) {        ResultSet rs = null;        try {            rs = PST.executeQuery();        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return rs;    }    public static void closeConn(Connection conn) {        if (conn != null) {            try {                conn.close();            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }    public static void closePST(PreparedStatement PST) {        if (PST != null) {            try {                PST.close();            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }    public static void closeRS(ResultSet rs) {        if (rs != null) {            try {                rs.close();            } catch (SQLException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }    }}

Test1 用到数据库

import java.io.File;  import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.HashMap;import java.util.Hashtable;  import java.util.Map;import com.google.zxing.BarcodeFormat;  import com.google.zxing.EncodeHintType;  import com.google.zxing.MultiFormatWriter;  import com.google.zxing.common.BitMatrix;  @SuppressWarnings("unchecked")public class Test {      public static void main(String[] args) throws Exception {        //二维码封装链接        String text = "http://192.168.1.66:18080/x5/UI2/v_/elevator/mainActivity.w?device=m&id=";          int width = 300;          int height = 300;          //二维码的图片格式          String format = "png";          Hashtable hints = new Hashtable();          //内容所使用编码          hints.put(EncodeHintType.CHARACTER_SET, "utf-8");          Map<String,String> ids = getIds();        for(String id : ids.keySet()){                BitMatrix bitMatrix = new MultiFormatWriter().encode(text+id,                      BarcodeFormat.QR_CODE, width, height, hints);              id = id.replace("/", "$");             //二维码生成路径              File outputFile = new File("d:"+File.separator+"QR2"+File.separator + id + ".png");             MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);        }    }      public static Map<String,String> getIds(){        Map<String,String> ids = new HashMap<String,String>();        Connection conn = DB.getConnection();        //String sql = "select * from elevatorinfor";        String sql = "SELECT * FROM elevatorinfor WHERE department LIKE '%物业%' AND address='=碧水蓝湾'";        PreparedStatement PST = DB.createPST(conn, sql);        ResultSet rs = DB.getRs(PST);        try {            while(rs.next()){                if(!rs.getString("id").equals("")){                    //id 格式为    梯津CFD0029 截取为CFD0029; 个人项目需要,根据需求修改                    ids.put(rs.getString("id").substring(2), rs.getString("department")+rs.getString("address"));                }            }        } catch (SQLException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return ids;    }}  

Test2 把链接封装成二维码

import java.io.File;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.HashMap;import java.util.Hashtable;import java.util.Map;import com.google.zxing.BarcodeFormat;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatWriter;import com.google.zxing.common.BitMatrix;public class TestQx{    public static void main(String[] args) throws Exception {        //地址生成二维码        String text = "http://ad1.tslanpu.cn:18080/x5/UI2/v_/qianxi/Index.w?device=m";        int width = 300;          int height = 300;          //二维码的图片格式          String format = "png";          Hashtable hints = new Hashtable();          //内容所使用编码          hints.put(EncodeHintType.CHARACTER_SET, "utf-8");        BitMatrix bitMatrix = new MultiFormatWriter().encode(text,               BarcodeFormat.QR_CODE, width, height, hints);        //二维码生成路径         File outputFile = new File("d:"+File.separator+"QX"+File.separator + "名字" +     ".png");           MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);}

用到的jar包

core-3.1.0.jar

0 0