美文网首页
Java生成二维码

Java生成二维码

作者: lclandld | 来源:发表于2020-02-17 10:22 被阅读0次

1、添加依赖包

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

2、生成二维码图片的工具类

package com.smartsite.util;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.smartsite.base.Constant;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.net.URL;

@Slf4j
public class CardGraphicsUtil {
   private CardGraphicsUtil() {
       super();
   }

   public static final String FONT = "宋体";
   public static final Color HUAXI_COLOR_GREEN = new Color(0, 122, 55);
   private static BufferedImage image;
   //图片的宽度
   private static final int imageWidth = 430;
   //图片的高度
   private static final int imageHeight = 250;

   /**
    * 生成名片
    *
    * @param qrUrl           二维码url
    * @param logoUrl         logo url
    * @param title           标题
    * @param backgroundColor 背景色
    * @param foreColor       前景色
    * @param items           显示内容
    * @return
    */
   public static BufferedImage generate(String qrUrl, String logoUrl, String title, Color backgroundColor, Color foreColor, Item... items) {
       if (null == qrUrl) {
           qrUrl = "";
       }
       if (null == logoUrl) {
           logoUrl = "";
       }
       if (null == title) {
           title = "";
       }
       if (null == items) {
           items = new Item[0];
       }
       if(null == backgroundColor){
           backgroundColor = Color.black;
       }
       if(null == foreColor){
           foreColor = Color.white;
       }
       //头部高度
       int H_title = 50;
       image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
       //画布背景
       Graphics2D main = image.createGraphics();
       //设置图片的背景色
       main.setColor(backgroundColor);
       main.fillRect(0, 0, imageWidth, imageHeight);

       //logo
       if (!ComUtil.isEmpty(logoUrl) && (logoUrl.toLowerCase().startsWith("http://") || logoUrl.toLowerCase().startsWith("https://"))){
           Graphics dPic = image.getGraphics();
           BufferedImage dimg = null;
           try {
               dimg = javax.imageio.ImageIO.read(new URL(logoUrl));
           } catch (Exception e) {
               log.error(e.getMessage(),e);
           }
           if (dimg != null) {
               dPic.setClip(new RoundRectangle2D.Double(10, 5, 40, 40, 0, 0));
               dPic.drawImage(dimg, 10, 5, 40, 40, null);
               dPic.dispose();
           }
       }

       //标题
       Graphics titleImg = image.createGraphics();
       //设置区域颜色
       titleImg.setColor(backgroundColor);
       //填充区域并确定区域大小位置
       titleImg.fillRect(50, 0, imageWidth - 50, H_title);
       //设置字体颜色,先设置颜色,再填充内容
       titleImg.setColor(foreColor);
       //设置字体
       Font titleFont = new Font(FONT, Font.BOLD, 18);
       titleImg.setFont(titleFont);
       titleImg.drawString(title, 60, 35);

       //横杠
       Graphics lineImg = image.createGraphics();
       //设置区域颜色
       lineImg.setColor(foreColor);
       //填充区域并确定区域大小位置
       lineImg.fillRect(10, 50, imageWidth - 20, 1);

       if (items.length > 0) {
           //详细信息
           Graphics itemsImg = image.createGraphics();
           //设置区域颜色
           titleImg.setColor(backgroundColor);
           //填充区域并确定区域大小位置
           titleImg.fillRect(12, 60, imageWidth - 200, 340);
           for (int i = 0; i < items.length; i++) {
               Item item = items[i];
               if (ComUtil.isEmpty(item)) {
                   break;
               }
               //设置字体颜色,先设置颜色,再填充内容
               titleImg.setColor(foreColor);
               //设置字体
               Font itemFont = new Font(FONT, Font.PLAIN, 14);
               titleImg.setFont(itemFont);
               titleImg.drawString(item.getName() + Constant.COLON + item.getValue(), 20, 25 * i + 80);
           }
       }

       //插入二维码
       Graphics qrImg = image.getGraphics();
       BufferedImage bimg = null;
       try {
           QrConfig config = new QrConfig(180, 180);
           config.setBackColor(backgroundColor.getRGB());
           config.setForeColor(foreColor.getRGB());
           bimg = QrCodeUtil.generate(qrUrl, config);
       } catch (Exception e) {
           log.error(e.getMessage(), e);
       }
       if (bimg != null) {
           qrImg.drawImage(bimg, 240, 65, 180, 180, null);
           qrImg.dispose();
       }
       return image;
   }

   /**
    * 图片切圆角
    *
    * @param srcImage
    * @param radius
    * @return
    */
   public static BufferedImage setClip(BufferedImage srcImage, int radius) {
       int width = srcImage.getWidth();
       int height = srcImage.getHeight();
       BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
       Graphics2D gs = image.createGraphics();

       gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
       gs.setClip(new RoundRectangle2D.Double(0, 0, width, height, radius, radius));
       gs.drawImage(srcImage, 0, 0, null);
       gs.dispose();
       return image;
   }



   public static Color getColor(int rgb) {
       return new Color(rgb);
   }

   /**
    * r,g,b-> int
    * @param r
    * @param g
    * @param b
    * @return rgb整型值
    */
   public static int getColor(int r,int g,int b) {
       return ((0xFF << 24)|(r << 16)|(g << 8)|b);
   }


   @Data
   @AllArgsConstructor
   public static class Item {
       private String name;
       private String value;
   }
}

3、Controller 接口

   /**
     *获取二维码接口
     */
    @ApiOperation(value = "qr")
    @Pass
    @GetMapping("/qr")
    public void qr(HttpServletResponse response) throws IOException {
        checkLocationService.generateQrCode(response);
    }

4、Services

   /**
     * 生成二维码
     * @param response
     * @throws IOException
     */
    @Override
    public void generateQrCode(HttpServletResponse response)throws IOException {
        ServletOutputStream os = response.getOutputStream();
        CardGraphicsUtil.Item[] items = new CardGraphicsUtil.Item[]{
                new CardGraphicsUtil.Item("001号配电箱","001号配电箱"),
                new CardGraphicsUtil.Item("巡检项目","配电箱"),
                new CardGraphicsUtil.Item("规格","一级配电箱"),
                new CardGraphicsUtil.Item("位置","1号楼"),
                new CardGraphicsUtil.Item("楼层","5F"),
                new CardGraphicsUtil.Item("负责人","王三张(13888888888)"),
                new CardGraphicsUtil.Item("负责人","李四(13888888888)")
        };
        //生成名片
        BufferedImage card = CardGraphicsUtil.generate("\"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1581913301580&di=f1e50a119aa7683fa221c145576a1cc1&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F78%2F52%2F01200000123847134434529793168.jpg\"", "\"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1581913301580&di=f1e50a119aa7683fa221c145576a1cc1&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F78%2F52%2F01200000123847134434529793168.jpg\"","二维码的title", CardGraphicsUtil.HUAXI_COLOR_GREEN, Color.white, items);

        //圆角处理
        card=CardGraphicsUtil.setClip(card,30);

        ImageIO.write(card,"PNG",os);
        os.flush();
        os.close();
    }

5、最后效果图

QR.png

注意一下,在实际Linux系统部署的时候,遇到了乱码的问题,是因为Linux系统差一个相应的字体,代码中用到的是宋体,直接在C:\Windows\Fonts下找到宋体的ttf,将其拷贝到Linux系统下的Java安装的相应路径下(/usr/java/jdk1.8.0_211-amd64/jre/lib/fonts),重启Linux即可生效

相关文章

网友评论

      本文标题:Java生成二维码

      本文链接:https://www.haomeiwen.com/subject/pypboctx.html