Java生成和解析二维码,支持logo图片

Java生成二维码,支持图片和输出流,支持添加logo图片。

注意:添加Logo图片时,图片不可过大,否则可能生成二维码失败。

以下为完整代码:

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
 
import javax.imageio.ImageIO;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 
/**
 * <p>Title:QRCodeUtil </p>
 * <p>Description: 二维码生成工具类</p>
 * @author Administrator
 * @version 
 * @since 
 */
public final class QRCodeUtil extends LuminanceSource {
 
    private static final Logger logger = LoggerFactory.getLogger(QRCodeUtil.class);
 
    // 二维码颜色-黑色
    private static final int BLACK = 0xFF000000;
    // 二维码颜色-白色
    private static final int WHITE = 0xFFFFFFFF;
 
    private final BufferedImage image;
    private final int left;
    private final int top;
    
    // logo图片默认宽高
    private static final int LOGO_IMG_WIDTH = 50;
    private static final int LOGO_IMG_HEIGHT = 50;
 
    public QRCodeUtil(BufferedImage image) {
        this(image, 0, 0, image.getWidth(), image.getHeight());
    }
 
    public QRCodeUtil(BufferedImage image, int left, int top, int width, int height) {
        super(width, height);
        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        if (left + width > sourceWidth || top + height > sourceHeight) {
            throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
        }
        for (int y = top; y < top + height; y++) {
            for (int x = left; x < left + width; x++) {
                if ((image.getRGB(x, y) & 0xFF000000) == 0) {
                    image.setRGB(x, y, 0xFFFFFFFF); // = white
                }
            }
        }
        this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
        this.image.getGraphics().drawImage(image, 0, 0, null);
        this.left = left;
        this.top = top;
    }
 
    @Override
    public byte[] getRow(int y, byte[] row) {
        if (y < 0 || y >= getHeight()) {
            throw new IllegalArgumentException("Requested row is outside the image: " + y);
        }
        int width = getWidth();
        if (row == null || row.length < width) {
            row = new byte[width];
        }
        image.getRaster().getDataElements(left, top + y, width, 1, row);
        return row;
    }
 
    @Override
    public byte[] getMatrix() {
        int width = getWidth();
        int height = getHeight();
        int area = width * height;
        byte[] matrix = new byte[area];
        image.getRaster().getDataElements(left, top, width, height, matrix);
        return matrix;
    }
 
    @Override
    public boolean isCropSupported() {
        return true;
    }
 
    @Override
    public LuminanceSource crop(int left, int top, int width, int height) {
        return new QRCodeUtil(image, this.left + left, this.top + top, width, height);
    }
 
    @Override
    public boolean isRotateSupported() {
        return true;
    }
 
    @Override
    public LuminanceSource rotateCounterClockwise() {
        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
        BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
        Graphics2D g = rotatedImage.createGraphics();
        g.drawImage(image, transform, null);
        g.dispose();
        int width = getWidth();
        return new QRCodeUtil(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
    }
    
    /***********************************************************************************************************
     ************************************************ 生成二维码 ************************************************
     ***********************************************************************************************************/
    
    /**
     * 生成指定宽高和格式的二维码图片
     *
     * @param text
     *            文本内容
     * @param width
     *            输出图片宽
     * @param height
     *            输出图片高
     * @param format
     *            图片格式:png,jpg,gif
     * @param outputFile
     *            输出的二维码图片
     * @throws Exception
     */
    public static void generateQRCode(String text, int width, int height, String format, File outputFile)
            throws Exception {
        BitMatrix bitMatrix = getBitMatrix(text, width, height);
        writeToFile(bitMatrix, format, outputFile);
    }
 
    /**
     * 生成指定宽高和格式的二维码图片流
     * 
     * @param text
     *            文本内容
     * @param width
     *            输出图片宽
     * @param height
     *            输出图片高
     * @param format
     *            图片格式:png,jpg,gif
     * @param outputStream
     *            输出流
     * @throws Exception
     */
    public static void generateQRCode(String text, int width, int height, String format, OutputStream outputStream)
            throws Exception {
        BitMatrix bitMatrix = getBitMatrix(text, width, height);
        writeToStream(bitMatrix, format, outputStream);
    }
    
    /**
     * 生成指定宽高和格式的二维码图片,可添加logo图片(logo图片过大可能会生成失败)
     * 
     * @param text
     *            文本内容
     * @param width
     *            输出图片宽
     * @param height
     *            输出图片高
     * @param format
     *            图片格式:png,jpg,gif
     * @param outputFile
     *            输出的二维码图片
     * @param logoImageFile
     *            logo图片
     * @param compress
     *            是否压缩Logo,如果压缩,logo图片最大宽高为LOGO_IMG_WIDTH和LOGO_IMG_HEIGHT
     * @throws Exception
     */
    public static void generateQRCode(String text, int width, int height, String format, File outputFile,
            File logoImageFile, boolean compress) throws Exception {
        BitMatrix bitMatrix = getBitMatrix(text, width, height);
        writeToFile(bitMatrix, format, outputFile, logoImageFile, compress);
    }
 
    /**
     * 生成指定宽高和格式的二维码图片流,可添加logo图片(logo图片过大可能会生成失败)
     * 
     * @param text
     *            文本内容
     * @param width
     *            输出图片宽
     * @param height
     *            输出图片高
     * @param format
     *            图片格式:png,jpg,gif
     * @param outputStream
     *            输出流
     * @param logoImageFile
     *            logo图片
     * @param compress
     *            是否压缩Logo,如果压缩,logo图片最大宽高为LOGO_IMG_WIDTH和LOGO_IMG_HEIGHT
     * @throws Exception
     */
    public static void generateQRCode(String text, int width, int height, String format, OutputStream outputStream,
            File logoImageFile, boolean compress) throws Exception {
        BitMatrix bitMatrix = getBitMatrix(text, width, height);
        writeToStream(bitMatrix, format, outputStream, logoImageFile, compress);
    }
    
    /**
     * 生成二维码图片
     * 
     * @param matrix
     *            矩阵对象
     * @param format
     *            图片格式:png,jpg,gif
     * @param file
     *            输出的文件完整路径
     * @throws IOException
     */
    private 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);
        }
    }
    
    /**
     * 生成二维码图片,可添加logo图片
     * 
     * @param matrix
     *            矩阵对象
     * @param format
     *            图片格式:png,jpg,gif
     * @param outputFile
     *            输出的二维码图片
     * @param logoImageFile
     *            logo图片
     * @param compress
     *            是否压缩Logo,如果压缩,logo图片最大宽高为LOGO_IMG_WIDTH和LOGO_IMG_HEIGHT
     * @throws Exception
     */
    private static void writeToFile(BitMatrix matrix, String format, File outputFile, File logoImageFile,
            boolean compress) throws Exception {
        BufferedImage image = toBufferedImage(matrix);
        if (logoImageFile != null && logoImageFile.exists()) {
            BufferedImage logoImage = ImageIO.read(logoImageFile);
            insertImage(image, logoImage, compress);
        }
        if (!ImageIO.write(image, format, outputFile)) {
            throw new IOException("Could not write an image of format " + format + " to " + outputFile);
        }
    }
    
    /**
     * 生成二维码图片流
     * 
     * @param matrix
     *            矩阵对象
     * @param format
     *            图片格式:png,jpg,gif
     * @param stream
     *            输出流
     * @throws IOException
     */
    private 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);
        }
    }
 
    /**
     * 生成二维码图片流,可添加logo图片
     * 
     * @param matrix
     *            矩阵对象
     * @param format
     *            图片格式:png,jpg,gif
     * @param stream
     *            输出流
     * @param logoImageFile
     *            logo图片
     * @param compress
     *            是否压缩Logo,如果压缩,logo图片最大宽高为LOGO_IMG_WIDTH和LOGO_IMG_HEIGHT
     * @throws Exception
     */
    private static void writeToStream(BitMatrix matrix, String format, OutputStream stream, File logoImageFile,
            boolean compress) throws Exception {
        BufferedImage image = toBufferedImage(matrix);
        if (logoImageFile != null && logoImageFile.exists()) {
            BufferedImage logoImage = ImageIO.read(logoImageFile);
            insertImage(image, logoImage, compress);
        }
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
    
    /**
     * 为二维码添加Logo图片
     * 
     * @param bufferedImage
     *            二维码
     * @param logoImage
     *            logo图片
     * @param compress
     *            是否压缩Logo,如果压缩,logo图片最大宽高为LOGO_IMG_WIDTH和LOGO_IMG_HEIGHT
     * @throws Exception
     */
    private static void insertImage(BufferedImage bufferedImage, BufferedImage logoImage, boolean compress)
            throws Exception {
        int width = logoImage.getWidth(null);
        int height = logoImage.getHeight(null);
 
        Image src = logoImage;
        if (compress) {
            if (width > LOGO_IMG_WIDTH) {
                width = LOGO_IMG_WIDTH;
            }
            if (height > LOGO_IMG_HEIGHT) {
                height = LOGO_IMG_HEIGHT;
            }
            Image image = logoImage.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;
        }
        Graphics2D graph = bufferedImage.createGraphics();
        int x = (bufferedImage.getWidth() - width) / 2;
        int y = (bufferedImage.getHeight() - 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();
    }
    
    /**
     * 转换 BitMatrix 为 BufferedImage
     * 
     * @param matrix
     *            矩阵对象
     * @return BufferedImage
     */
    private 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;
    }
    
    /**
     * 创建矩阵对象BitMatrix
     * 
     * @param text
     *            文本内容
     * @param width
     *            宽度
     * @param height
     *            高度
     * @return BitMatrix
     * @throws WriterException
     */
    private static BitMatrix getBitMatrix(String text, int width, int height) throws WriterException {
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 指定编码格式
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);// 指定纠错等级
        hints.put(EncodeHintType.MARGIN, 1); // 白边大小,取值范围0~4
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        return bitMatrix;
    }
 
    /***********************************************************************************************************
     ************************************************ 解析二维码 ************************************************
     ***********************************************************************************************************/
 
    /**
     * 解析二维码图片内容
     *
     * @param filePath
     *            二维码图片路径
     * @return 文本内容
     */
    public static String parseQRCode(String filePath) {
        String content = "";
        try {
            File file = new File(filePath);
            BufferedImage image = ImageIO.read(file);
            LuminanceSource source = new QRCodeUtil(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            MultiFormatReader formatReader = new MultiFormatReader();
            Result result = formatReader.decode(binaryBitmap, hints);
 
            // logger.info("result 为:" + result.toString());
            // logger.info("resultFormat 为:" + result.getBarcodeFormat());
            // logger.info("resultText 为:" + result.getText());
            // 设置返回值
            content = result.getText();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return content;
    }
    
    /***********************************************************************************************************
     ************************************************ 其他辅助方法 **********************************************
     ***********************************************************************************************************/
   
    /**
     * InputStream转OutputStream
     * 
     * @param input
     *            InputStream
     * @return OutputStream
     * @throws Exception
     */
    public static ByteArrayOutputStream inputStreamToOutputStream(InputStream input) throws Exception {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        int ch;
        while ((ch = input.read()) != -1) {
            swapStream.write(ch);
        }
        return swapStream;
    }
 
    /**
     * OutputStream转InputStream
     * 
     * @param output
     *            OutputStream
     * @return
     * @throws Exception
     */
    public static ByteArrayInputStream outputStreamToInputStream(OutputStream output) throws Exception {
        return new ByteArrayInputStream(((ByteArrayOutputStream) output).toByteArray());
    }
 
    /**
     * InputStream转String字符串
     * 
     * @param input
     *            InputStream
     * @return String字符串
     * @throws Exception
     */
    public static String inputStreamToString(InputStream input) throws Exception {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        int ch;
        while ((ch = input.read()) != -1) {
            swapStream.write(ch);
        }
        return swapStream.toString();
    }
 
    /**
     * OutputStream转String字符串
     * 
     * @param output
     *            OutputStream
     * @return String字符串
     * @throws Exception
     */
    public static String outputStreamToString(OutputStream output) throws Exception {
        return new ByteArrayInputStream(((ByteArrayOutputStream) output).toByteArray()).toString();
    }
 
    /**
     * String字符串转InputStream
     * 
     * @param input
     *            String字符串
     * @return InputStream
     * @throws Exception
     */
    public static ByteArrayInputStream stringToInputStream(String input) throws Exception {
        return new ByteArrayInputStream(input.getBytes());
    }
 
    /**
     * String字符串转OutputStream
     * 
     * @param input
     *            String字符串
     * @return OutputStream
     * @throws Exception
     */
    public static ByteArrayOutputStream stringToOutputStream(String input) throws Exception {
        return inputStreamToOutputStream(stringToInputStream(input));
    }
 
//    public static void main(String[] args) {
//        String text = "hello world!"; // 随机生成的12位验证码
//        System.out.println("随机生成的12位验证码为: " + text);
//        int width = 300; // 二维码图片的宽
//        int height = 300; // 二维码图片的高
//        String format = "png"; // 二维码图片的格式
//        try {
//            // 生成二维码图片,并返回图片路径
//            File file = new File("D:/new.png");
//            generateQRCode(text, width, height, format, file, new File("D:/q.png"), true);
//            System.out.println("生成二维码的图片路径: " + file.getAbsolutePath());
//
//            String content = parseQRCode(file.getAbsolutePath());
//            System.out.println("解析出二维码的图片的内容为: " + content);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
 
}

需要引入的jar包:

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>

https://blog.csdn.net/jinqilin721/article/details/88894682

更新时间:2020-05-21 19:36:52

本文由 新逸Cary 创作,如果您觉得本文不错,请随意赞赏
采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
原文链接:https://blog.xinac.cn/archives/java生成和解析二维码支持logo图片.html
最后更新:2020-05-21 19:36:52

评论

Your browser is out of date!

Update your browser to view this website correctly. Update my browser now

×