使用zxing创建二维码

2020/12/19 07:19
阅读数 78

1,添加依赖

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

2,创建二维码代码


import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.io.IOUtils;
import org.springframework.util.Assert;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description QRCodeUtil
 * @Author dsf
 * @Date 2020/12/18 13:12
 * @Version V1.0
 **/
public class QRCodeUtil {

    public enum Colors {
        BLUE(0xFF40BAD0),
        RED(0xFFE91C43),
        PURPLE(0xFF8A4F9E),
        ORANGE(0xFFF4B13D),
        WHITE(0xFFFFFFFF),
        BLACK(0xFF000000);

        private final int argb;
        Colors(final int argb){
            this.argb = argb;
        }
        public int getArgb(){
            return argb;
        }
    }

    public enum ContentType {
        IMAGE_PNG("image/png"),
        IMAGE_JPEG("image/jpeg");
        private final String contentType;
        ContentType(final String contentType){
            this.contentType = contentType;
        }

        public String getFormat(){
            return getContentType().split("/")[1] ;
        }

        public String getContentType() {
            return contentType;
        }
    }

    /**
     * 创建二维码
     * @param  content 二维码承载内容
     * @param  width   二维码的宽度(像素)
     * @param  height  二维码的高度(像素)
     *
     * */
    public static BufferedImage createQrCode(String content,int width,int height){
        //设置图片的文字编码以及内边框
        Map<EncodeHintType, Object> hints = new HashMap<>();
        //编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //边框距
        hints.put(EncodeHintType.MARGIN, 1);
        //纠错等级L,M,Q,H
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

        BitMatrix bitMatrix;
        try {
            //参数分别为:编码内容、编码类型、图片宽度、图片高度,设置参数
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
            //设置二维码图片前景色和背景色颜色
            MatrixToImageConfig config = new MatrixToImageConfig(Colors.WHITE.getArgb(), Colors.ORANGE.getArgb());
            //生成二维码图片
            BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
            //MatrixToImageWriter.writeToPath(bitMatrix, format, file, config);
            return qrImage ;
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null ;
    }

    /**
     * 给二维码添加logo
     * */
    public static ByteArrayOutputStream addLogo(BufferedImage qrImage, File logoFile) throws Exception {
        return addLogo( qrImage, logoFile,ContentType.IMAGE_JPEG) ;
    }

    /**
     * 给二维码添加logo
     * */
    public static ByteArrayOutputStream addLogo(BufferedImage qrImage, File logoFile,ContentType toImageType) throws Exception {
        Assert.isNull(qrImage,"未传入二维码数据,不能继续");
        //载入logo
        BufferedImage logImage =  ImageIO.read(logoFile);
        //计算二维码和logo之间的高度和宽度差
        int deltaHeight = qrImage.getHeight() - logImage.getHeight();
        int deltaWidth = qrImage.getWidth() - logImage.getWidth();

        // 初始化组合图像(将二维码和logo相组合)
        BufferedImage combined = new BufferedImage(qrImage.getHeight(), qrImage.getWidth(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) combined.getGraphics();
        // 将二维码写入新图像
        g.drawImage(qrImage, 0, 0, null);
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
        //将logo插入图像中并居中
        g.drawImage(logImage, (int) Math.round(deltaWidth / 2), (int) Math.round(deltaHeight / 2), null);

        //将组合的图像输出
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        ImageIO.write(combined, toImageType.getFormat(), os);
        return os ;
    }

    /**
     * @param imageStream 要输出的图片刘
     * @param formatName 图片格式,例如:png,jpg
     * */
    public static void saveImage(InputStream imageStream, OutputStream outputStream, String formatName) throws IOException {
        ImageIO.write(ImageIO.read(imageStream), formatName, outputStream);
    }

    /**
     * 将二维码图片写出到响应流中
     * */
    public static void write2Response(byte[] imageBytes,HttpServletResponse response,ContentType contentType) throws IOException {
        // 不允许缓存
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        //告诉浏览器返回的是图片流
        response.setContentType(contentType.contentType);
        IOUtils.write(imageBytes,response.getOutputStream());
    }

    /**
     * 读取二维码
     * */
    public static void readQrCode(File file) throws IOException, NotFoundException {
        MultiFormatReader read = new MultiFormatReader();
        BufferedImage image=ImageIO.read(file);
        Binarizer binarizer=new HybridBinarizer(new BufferedImageLuminanceSource(image));
        BinaryBitmap binaryBitmap=new BinaryBitmap(binarizer);

        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        Result res=read.decode(binaryBitmap,hints);
        System.out.println(res.toString());
        System.out.println(res.getBarcodeFormat());
        System.out.println(res.getText());
    }

    public static void main(String[] args) throws IOException {
        String content = "http://www.abc.com/a/b?name=2d" ;
        int width = 300 ;
        int height = 300 ;
        //创建二维码
        BufferedImage bufferedImage = createQrCode(content,width,height) ;
        //写入文件
        FileOutputStream outputStream = new FileOutputStream(new File("adb.jpg")) ;
        ImageIO.write(bufferedImage,"jpg",outputStream) ;
    }
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部