Java generates QR codes to add logo and text functions


Without further ado, I posted the code directly to you. The specific code is as follows:

package com.luo.wctweb.util;
 import java.awt.Color;
 import java.awt.Font;
 import java.awt.Graphics2D;
 import java.awt.image.BufferedImage;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
 import javax.imageio.ImageIO;
 import javax.servlet.http.HttpServletRequest;
 import com.google.zxing.BarcodeFormat;
 import com.google.zxing.EncodeHintType;
 import com.google.zxing.MultiFormatWriter;
 import com.google.zxing.WriterException;
 import com.google.zxing.common.BitMatrix;
 import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 import com.lz.lsf.util.Base64;
 /** * @Description: (2 D code ) * @author : luoguohui * @date : 2015-10-29  In the afternoon 05:27:13 */
 public class ZXingCode {
  private static final int QRCOLOR = 0xFF000000; // Default is black
  private static final int BGWHITE = 0xFFFFFFFF; // The background color
  public static void main(String[] args) throws WriterException
  {
   try
   {
    getLogoQRCode("https://www.baidu.com/", null, " Jump to Baidu 2 D code ");
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
  }
  /** *  Generated with logo the 2 D code pictures  * * @param qrPic * @param logoPic */
  public static String getLogoQRCode(String qrUrl,HttpServletRequest request,String productName)
  {
 // String filePath = request.getSession().getServletContext().getRealPath("/") + "resources/images/logoImages/llhlogo.png";
   //filePath is 2 D code logo But in practice we put the path under one of the project paths, so the path USES the one above, just comment out the following
   String filePath = "C:/Users/luoguohui/Desktop/78310a55b319ebc4fa3aef658126cffc1f17168f.jpg"; //TODO
   String content = qrUrl;
   try
   {
    ZXingCode zp = new ZXingCode();
    BufferedImage bim = zp.getQR_CODEBufferedImage(content, BarcodeFormat.QR_CODE, 400, 400, zp.getDecodeHintType());
    return zp.addLogo_QRCode(bim, new File(filePath), new LogoConfig(), productName);
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
   return null;
  }
  /** *  to 2 Dimension code image addition Logo * * @param qrPic * @param logoPic */
  public String addLogo_QRCode(BufferedImage bim, File logoPic, LogoConfig logoConfig, String productName)
  {
   try
   {
    /** *  read 2 Dimension code images and build drawing objects  */
    BufferedImage image = bim;
    Graphics2D g = image.createGraphics();
    /** *  read Logo The picture  */
    BufferedImage logo = ImageIO.read(logoPic);
    /** *  Set up the logo The size of the , I set as 2 Dimension code picture 20%, Because it's too big to cover up 2 D code  */
    int widthLogo = logo.getWidth(null)>image.getWidth()*3/10?(image.getWidth()*3/10):logo.getWidth(null),
     heightLogo = logo.getHeight(null)>image.getHeight()*3/10?(image.getHeight()*3/10):logo.getWidth(null);
    /** * logo In the center  */
    int x = (image.getWidth() - widthLogo) / 2;
    int y = (image.getHeight() - heightLogo) / 2;
    /** * logo In the bottom right hand corner  * int x = (image.getWidth() - widthLogo); * int y = (image.getHeight() - heightLogo); */
    // Start drawing pictures
    g.drawImage(logo, x, y, widthLogo, heightLogo, null);
 // g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
 // g.setStroke(new BasicStroke(logoConfig.getBorder()));
 // g.setColor(logoConfig.getBorderColor());
 // g.drawRect(x, y, widthLogo, heightLogo);
    g.dispose();
    // Add the name of the item. The name of the item should not be too long. If it's too long, it will automatically intercept it
    if (productName != null && !productName.equals("")) {
     // New picture, bring it logo the 2 The dimension code is followed by text
     BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
     Graphics2D outg = outImage.createGraphics();
     // draw 2 Dimension code to new panel
     outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
     // Draw text to the new panel
     outg.setColor(Color.BLACK);
     outg.setFont(new Font(" Song typeface ",Font.BOLD,30)); // Font, type, font size
     int strWidth = outg.getFontMetrics().stringWidth(productName);
     if (strWidth > 399) {
 // // If it's too long, cut out the front
 // outg.drawString(productName, 0, image.getHeight() + (outImage.getHeight() - image.getHeight())/2 + 5 ); // Draw the text
      // Wrap lines if they are too long
      String productName1 = productName.substring(0, productName.length()/2);
      String productName2 = productName.substring(productName.length()/2, productName.length());
      int strWidth1 = outg.getFontMetrics().stringWidth(productName1);
      int strWidth2 = outg.getFontMetrics().stringWidth(productName2);
      outg.drawString(productName1, 200 - strWidth1/2, image.getHeight() + (outImage.getHeight() - image.getHeight())/2 + 12 );
      BufferedImage outImage2 = new BufferedImage(400, 485, 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(" Song typeface ",Font.BOLD,30)); // Font, type, font size
      outg2.drawString(productName2, 200 - strWidth2/2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight())/2 + 5 );
      outg2.dispose();
      outImage2.flush();
      outImage = outImage2;
     }else {
      outg.drawString(productName, 200 - strWidth/2 , image.getHeight() + (outImage.getHeight() - image.getHeight())/2 + 12 ); // Draw the text
     }
     outg.dispose();
     outImage.flush();
     image = outImage;
    }
    logo.flush();
    image.flush();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.flush();
    ImageIO.write(image, "png", baos);
    //2 The path generated by the dimension code, but in the actual project, we generated this 2 Dimension code is displayed on the interface, so the following line breaks can be commented out
    // And you can see that this method ends up returning this 2 D yards imageBase64 string
    // Front end with  <img src="data:image/png;base64,${imageBase64QRCode}"/>  Among them ${imageBase64QRCode} The corresponding 2 D yards imageBase64 string
    ImageIO.write(image, "png", new File("C:/Users/luoguohui/Desktop/TDC-" + new Date().getTime() + "test.png")); //TODO
    String imageBase64QRCode = Base64.byteArrayToBase64(baos.toByteArray());
    baos.close();
    return imageBase64QRCode;
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
   return null;
  }
  /** *  Build initialization 2 D code  * * @param bm * @return */
  public BufferedImage fileToBufferedImage(BitMatrix bm)
  {
   BufferedImage image = null;
   try
   {
    int w = bm.getWidth(), h = bm.getHeight();
    image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x < w; x++)
    {
     for (int y = 0; y < h; y++)
     {
      image.setRGB(x, y, bm.get(x, y) ? 0xFF000000 : 0xFFCCDDEE);
     }
    }
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
   return image;
  }
  /** *  generate 2 D code bufferedImage The picture  * * @param content *  The coding content  * @param barcodeFormat *  The encoding type  * @param width *  Image width  * @param height *  Picture height  * @param hints *  Set the parameters  * @return */
  public BufferedImage getQR_CODEBufferedImage(String content, BarcodeFormat barcodeFormat, int width, int height, Map<EncodeHintType, ?> hints)
  {
   MultiFormatWriter multiFormatWriter = null;
   BitMatrix bm = null;
   BufferedImage image = null;
   try
   {
    multiFormatWriter = new MultiFormatWriter();
    //  The sequence of parameters is as follows: encoding content, encoding type, width of image generated, height of image generated, and setting parameters
    bm = multiFormatWriter.encode(content, barcodeFormat, width, height, hints);
    int w = bm.getWidth();
    int h = bm.getHeight();
    image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    //  Begin to use 2 Dimension code data creation Bitmap Pictures, respectively set to black ( 0xFFFFFFFF White () 0xFF000000 Two color)
    for (int x = 0; x < w; x++)
    {
     for (int y = 0; y < h; y++)
     {
      image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
     }
    }
   }
   catch (WriterException e)
   {
    e.printStackTrace();
   }
   return image;
  }
  /** *  Set up the 2 Format parameters for dimension codes  * * @return */
  public Map<EncodeHintType, Object> getDecodeHintType()
  {
   //  Used to set the QR2 D code parameter
   Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
   //  Set up the QR2 Error correction level of dimension code ( H Is the highest level) specific level of information
   hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
   //  Set encoding mode
   hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
   hints.put(EncodeHintType.MARGIN, 0);
   hints.put(EncodeHintType.MAX_SIZE, 350);
   hints.put(EncodeHintType.MIN_SIZE, 100);
   return hints;
  }
 }
  class LogoConfig
  {
   // logo Default border color
   public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;
   // logo Default border width
   public static final int DEFAULT_BORDER = 2;
   // logo The default size is for photos 1/5
   public static final int DEFAULT_LOGOPART = 5;
   private final int border = DEFAULT_BORDER;
   private final Color borderColor;
   private final int logoPart;
   /** * Creates a default config with on color {@link #BLACK} and off color * {@link #WHITE}, generating normal black-on-white barcodes. */
   public LogoConfig()
   {
    this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);
   }
   public LogoConfig(Color borderColor, int logoPart)
   {
    this.borderColor = borderColor;
    this.logoPart = logoPart;
   }
   public Color getBorderColor()
   {
    return borderColor;
   }
   public int getBorder()
   {
    return border;
   }
   public int getLogoPart()
   {
    return logoPart;
   }
  }