一维码 和 二维码 生成工具类

发布于 2019-06-26  1.06k 次阅读


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.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;
 
/**
        二维码 和 一维码 工具类
         <!-- 二维码生成 -->
         <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>
 */
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 final int BLACK = 0xff000000;
    private static final int WHITE = 0xFFFFFFFF;
 
    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));
    }
 
    /**
     * 生成RQ二维码
     *
     * @param str    内容
     * @param height 高度(px)
     * @author
     */
    public static BufferedImage getRQ(String str, Integer height) {
        if (height == null || height < 100) {
            height = 200;
        }
 
        try {
            // 文字编码
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
 
            BitMatrix bitMatrix = new MultiFormatWriter().encode(str,
                    BarcodeFormat.QR_CODE, height, height, hints);
 
            return toBufferedImage(bitMatrix);
 
            // 输出方式
            // 网页
            // ImageIO.write(image, "png", response.getOutputStream());
 
            // 文件
            // ImageIO.write(image, "png", file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 生成一维码(128)
     *
     * @param str  要存储的内容
     * @param width  宽度
     * @param height  高度
     * @return
     * @author
     */
    public static BufferedImage getBarcode(String str, Integer width,
                                           Integer height) {
 
        if (width == null || width < 200) {
            width = 200;
        }
 
        if (height == null || height < 50) {
            height = 50;
        }
 
        try {
            // 文字编码
            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
 
            BitMatrix bitMatrix = new MultiFormatWriter().encode(str,
                    BarcodeFormat.CODE_128, width, height, hints);
 
            return toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 生成二维码,写到文件中
     *
     * @param str 存储内容
     * @param height 高度
     * @param file  写入的文件
     * @throws IOException
     * @author
     */
    public static void getQRWriteFile(String str, Integer height, File file)
            throws IOException {
        BufferedImage image = getRQ(str, height);
        ImageIO.write(image, "png", file);
    }
 
    /**
     * 生成一维码,写到文件中
     *
     * @param str  存储的内容
     * @param height  高度
     * @param fileName  存入的文件名字
     * @param filePath  存入地址
     * @throws IOException
     * @author
     */
    public static void getBarcodeWriteFile(String str, Integer width,
                                           Integer height,String filePath ,String fileName) throws IOException {
        File file = new File(filePath + "\\" + fileName + ".jpg");
        BufferedImage image = getBarcode(str, width, height);
        ImageIO.write(image, "png", file);
    }
 
    /**
     * 转换成图片
     *
     * @param matrix
     * @return
     * @author
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_ARGB);
        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 String read(File file) {
 
        BufferedImage image;
        try {
            if (file == null || file.exists() == false) {
                throw new Exception(" File not found:" + file.getPath());
            }
 
            image = ImageIO.read(file);
 
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
 
            Result result;
 
            // 解码设置编码方式为:utf-8,
            Hashtable hints = new Hashtable();
            hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
 
            result = new MultiFormatReader().decode(bitmap, hints);
 
            return result.getText();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return null;
    }
 
 
 
//    public static void main(String[] args) throws Exception {
////        String text = "http://www.lianyinkeji.cn";
//
//        //含Logo,指定二维码图片名
////        QRCodeUtil.encode(text, "E:\\codebase\\zxing\\src\\main\\resources\\logo.png", "E:\\", "qrcode", true);
//        String content = "2222baidu一";
//        String logoPath = "C:\\Users\\Lenovo\\Desktop\\pay\\111.jpg";
//        String destPath = "C:\\Users\\Lenovo\\Desktop\\pay";
//        String fileName = "logo";
////        File file = new File("C:\\Users\\Lenovo\\Desktop\\pay\\test.png");
//        QRCodeUtil.getBarcodeWriteFile(content,300,100,destPath,"ErWeiMa");
////        QRCodeUtil.encode(content,logoPath,destPath,fileName,true);
//        //不含Logo
//        //QRCodeUtil.encode(text, null, "e:\\", true);
//
//        //含Logo,不指定二维码图片名
//        //QRCodeUtil.encode(text, "e:\\csdn.jpg", "e:\\", true);
//
//    }
}

公交车司机终于在众人的指责中将座位让给了老太太