天天看點

Zxing 生成帶logo的二維碼 下面放文字

生成的二維碼圖檔:

Zxing 生成帶logo的二維碼 下面放文字
package com.psd.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import javax.imageio.ImageIO;

import org.apache.commons.lang3.StringUtils;

import com.github.binarywang.utils.qrcode.MatrixToImageWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.awt.SunHints;

/**
 * 二維碼工具類
 * 
 * @ClassName: BarcodeUtils.java
 * @version: v1.0.0
 * @author: pll
 * @date: 2018年6月4日 下午2:51:54
 */
public class BarcodeUtils {

   private static final int QRCOLOR = 0xFF000000; // 二維碼顔色 預設是黑色
   private static final int BGWHITE = 0xFFFFFFFF; // 背景顔色

   private static final int WIDTH = 215; // 二維碼寬
   private static final int HEIGHT = 215; // 二維碼高

   private static final int WORDHEIGHT = 235; // 加文字二維碼高


   /**
    * 用于設定QR二維碼參數
    */
   private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
      private static final long serialVersionUID = 1L;
      {
         // 設定QR二維碼的糾錯級别(H為最進階别)具體級别資訊
         put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
         // 設定編碼方式
         put(EncodeHintType.CHARACTER_SET, "utf-8");
         put(EncodeHintType.MARGIN, 0);
      }
   };


   /**
    * 設定 Graphics2D 屬性  (抗鋸齒)
    * @param graphics2D
    */
   private static void setGraphics2D(Graphics2D graphics2D){
      graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
      Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
      graphics2D.setStroke(s);
   }


   /**
    * 生成二維碼圖檔存儲到filePath中
    * 
    * @param content
    *            二維碼内容
    * @param filePath
    *            成二維碼圖檔儲存路徑
    * @return
    */
   public static boolean createImg(String content, String filePath) {
      boolean flag = false;
      try {
         MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
         BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

         // 圖檔輸出路徑
         String code = content.split("=")[1]; // 裝置編号

         File file = new File(filePath + "//PSD" + code + ".jpg");
         if (!file.exists()) {
            // 如果檔案夾不存在則建立
            file.mkdirs();
         }

         // 輸出二維碼圖檔到檔案夾
         MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file);
         flag = true;

      } catch (IOException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }
      return flag;
   }


   /**
    * 把帶logo的二維碼下面加上文字
    * @param image
    * @param words
    * @return
    */
   private static BufferedImage insertWords(BufferedImage image,String words){
      // 新的圖檔,把帶logo的二維碼下面加上文字
      if (StringUtils.isNotEmpty(words)) {

         //建立一個帶透明色的BufferedImage對象
         BufferedImage outImage = new BufferedImage(WIDTH, WORDHEIGHT, BufferedImage.TYPE_INT_ARGB);
         Graphics2D outg = outImage.createGraphics();
         setGraphics2D(outg);

         // 畫二維碼到新的面闆
         outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
         // 畫文字到新的面闆
         Color color=new Color(183,183,183);
         outg.setColor(color);
         // 字型、字型、字号
         outg.setFont(new Font("微軟雅黑", Font.PLAIN, 18));
         //文字長度
         int strWidth = outg.getFontMetrics().stringWidth(words);
         //總長度減去文字長度的一半  (居中顯示)
         int wordStartX=(WIDTH - strWidth) / 2;
         //height + (outImage.getHeight() - height) / 2 + 12
         int wordStartY=HEIGHT+10;
         // 畫文字
         outg.drawString(words, wordStartX, wordStartY);
         outg.dispose();
         outImage.flush();
         return outImage;

                /*if (strWidth > 399) {
                    // 長度過長就截取前面部分 然後換行
                    String note1 = note.substring(0, note.length() / 2);
                    String note2 = note.substring(note.length() / 2, note.length());
                    int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                    int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                    outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(1000, 1120, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
               // 字型、字型、字号
                    outg2.setFont(new Font("宋體", Font.BOLD, 30));
               // 畫文字
                    outg2.drawString(note2, 200 - strWidth2 / 2,outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                } */
      }
      return null;
   }


   /**
    * @description 生成帶logo的二維碼圖檔 二維碼下面帶文字
    * @param logoFile loge圖檔的路徑
    * @param bgFile 背景圖檔的路徑
    * @param codeFile 圖檔輸出路徑
    * @param qrUrl 二維碼内容
    * @param words 二維碼下面的文字
    */
   public static void drawLogoQRCode(File logoFile,File bgFile, File codeFile, String qrUrl, String words) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 參數順序分别為:編碼内容,編碼類型,生成圖檔寬度,生成圖檔高度,設定參數
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

            // 開始利用二維碼資料建立Bitmap圖檔,分别設為黑(0xFFFFFFFF)白(0xFF000000)兩色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }

            //把logo畫到二維碼上面
            if (Objects.nonNull(logoFile) && logoFile.exists()) {
                // 建構繪圖對象
                Graphics2D g = image.createGraphics();
            setGraphics2D(g);
                // 讀取Logo圖檔
                BufferedImage logo = ImageIO.read(logoFile);
                // 開始繪制logo圖檔 等比縮放:(width * 2 / 10 height * 2 / 10)不需縮放直接使用圖檔寬高
            //width * 2 / 5 height * 2 / 5  logo繪制在中心點位置
                g.drawImage(logo, WIDTH * 2 / 5, HEIGHT * 2 / 5, logo.getWidth(), logo.getHeight(), null);
                g.dispose();
                logo.flush();
            }

            // 新的圖檔,把帶logo的二維碼下面加上文字
            image=insertWords(image,words);

            image.flush();
            ImageIO.write(image, "png", codeFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
   }
   
   public static void main(String[] args) {
      //logo
      File logoFile = new File("G://picture/03.png");
      //背景圖檔
      File bgFile = new File("G://picture/01.png");
      //生成圖檔
        File qrCodeFile = new File("G://picture/02.png");
        //二維碼内容
        String url = "https://w.url.cn/s/AYmfAV3";
        //二維碼下面的文字
        String words = "PSD000001";
        drawLogoQRCode(logoFile,bgFile, qrCodeFile, url, words);
   }

}