使用zxing建立二維碼

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) ;
    }
}
相關文章
相關標籤/搜索