java在底图上生成二维码以及文字

java在底图上生成二维码以及文字

1.添加依赖

<dependency>
   <groupId>cn.hutoolgroupId>
   <artifactId>hutool-extraartifactId>
   <version>5.4.3version>
dependency>
<dependency>
   <groupId>com.google.zxinggroupId>
   <artifactId>coreartifactId>
   <version>3.3.3version>
dependency>

2.工具类

package com.sunente.framework.qrcode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sunente.framework.assets.deviceAsset.bean.Device;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
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: 在图片上生成二维码并且在图片上添加文字response前端
 */
public class QRcodeImageFont {
    // 默认宽为300
    private static Integer width = 120;
    // 默认高为300
    private static Integer height = 120;
    // 默认二维码图片格式
    private static String imageFormat = "png";
    // 默认二维码字符编码
    private static String charType = "utf-8";

    // 容错等级 L、M、Q、H 其中 L 为最低, H 为最高
    private static ErrorCorrectionLevel corretionLevel = ErrorCorrectionLevel.M;
    // 二维码与图片的边缘
    private static Integer margin = 0;
    // 二维码参数
    private static Map<EncodeHintType, Object> encodeHits = new HashMap<EncodeHintType, Object>();

    // 初始化二维码的参数
    private static void initialParams() {
        // 字符编码
        encodeHits.put(EncodeHintType.CHARACTER_SET, charType);
        // 容错等级 L、M、Q、H 其中 L 为最低, H 为最高
        encodeHits.put(EncodeHintType.ERROR_CORRECTION, corretionLevel);
        // 二维码与图片边距 就是白边有多宽
        encodeHits.put(EncodeHintType.MARGIN, margin);
    }

    /***
     * 在一张背景图上添加二维码
     */
    public static void drawString(String code, HttpServletResponse response, byte[] bytes) throws Exception {
        BufferedImage image = addBaseMap(code,bytes);
        Graphics2D gd = image.createGraphics();
        // 5.设置对线段的锯齿状边缘处理
        gd.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        // 6.设置水印文字颜色
        gd.setColor(Color.black);
        // 7.设置水印文字Font
        gd.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        // 8.第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
        gd.drawString("设备编号:"+code, 140, 74);
        gd.dispose();
        // 9. 输出图片
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, imageFormat,outputStream );
        outputStream.flush();
        outputStream.close();
    }


    /**
     * 生成底图以及二维码
     * @param content 要生成的二维码字符串
     * @param bytes 底图的字节数组 可以通过其它形式生成 Image 对象
     * @return
     * @throws Exception
     */
    public static BufferedImage addBaseMap(String content,byte[] bytes) throws Exception {
        //1.数组转化为图片
        Image srcImg = ImageIO.read(new ByteArrayInputStream(bytes));
        //获取图片的宽
        int srcImgWidth = srcImg.getWidth(null);
        //获取图片的高
        int srcImgHeight = srcImg.getHeight(null);
        //2.生成底图
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufImg.createGraphics();
        g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
        //3.使用工具类生成二维码
        Image image = getBufferedImage(content);
        //4.将小图片绘到大图片上,15,45  表示你的小图片在大图片上的位置。
        g.drawImage(image, 15, 45, null);
        //设置颜色。
        g.setColor(Color.WHITE);
        g.dispose();
        return bufImg;
    }

    /**
     * 生成二维码
     * @param content
     * @return
     */
    public static BufferedImage getBufferedImage(String content) {
        initialParams();
        BufferedImage bufferedImage = null;
        try {
            //参数为 字符串参数 二维码格式 宽 高 二维码入参
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width,
                    height,encodeHits);
            bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
        return bufferedImage;
    }
}

3.controller请求测试

@ApiOperation("根据文件名下载")
@ApiImplicitParams({
		@ApiImplicitParam(name = "code", value = "code", dataType = "string", paramType = "query", required = true),
})
@GetMapping(value="/createNewQRCodeByCode")
public void createNewQRCodeByCode(HttpServletRequest request, HttpServletResponse response,String code){
	try{
	//因为我的照片都存在了minio所以就直接从minio获取就行了
		byte[] bytes = minioTemplate.getObject("733202765131681792.png");
		response.setHeader("content-disposition", "attachement;filename="+URLEncoder.encode(code, "utf-8"));
		response.setContentType("application/octet-stream;charset=UTF-8");
		QRcodeImageFont.drawString(code,response,bytes);
	}catch(Exception e){
		log.error("根据文件名下载时异常",e);
	}
}

参考了博主

https://blog.csdn.net/qq_38377774/article/details/108767573?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166392315716782390589650%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=166392315716782390589650&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v1~rank_v31_ecpm-6-108767573-null-null.142v50control_1,201v3control_1&utm_term=java%E5%9C%A8%E5%9B%BE%E7%89%87%E4%B8%8A%E7%94%9F%E6%88%90%E4%BA%8C%E7%BB%B4%E7%A0%81%E5%9B%BE%E7%89%87&spm=1018.2226.3001.4187

你可能感兴趣的:(java,servlet,前端)