Java 生成微信扫描的二维码,跳转到指定网址,图片增加二维码及文字水印

两种场景:
1、图片海报中加二维码
在这里插入图片描述

2、二维码中间加入指定图标

在这里插入图片描述

注意点:字体要再设置一下清晰度,要不特别模糊。
graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);

/**
 * @description 二维码控制器
 */
@RestController
public class QrcodeController {
    
    

    @Autowired
    ResourceLoader resourceLoader;

    /**
     * todo 每个用户一张二维码,里面的信息就是邀请码或者是userid
     *
     * @param userid MREAM5
     * @return void
     * @description 生成二维码
     * @Param response
     **/
    @GetMapping("/getQrcode")
    @ResponseBody
    public void getQrcode(@RequestParam("userid") String userid, HttpServletResponse response) throws Exception {
    
    
        String url = "http://www.biturd.com/pages/register/register";
        String inviteCode = getInviteCodeByUserId(userid);
        String content = url + "?invite_code=" + inviteCode;
//
//        String imgPath = "./test.jpg";
        Resource resource = resourceLoader.getResource("classpath:test.jpg");
        File imgFile = resource.getFile();
        // 海报图片
        BufferedImage outerImg = ImageIO.read(imgFile);

        Boolean needCompress = true;
        //图片海报outerImg中加二维码
        ByteArrayOutputStream out = QRCodeUtil.encodeIOWith(content, outerImg, needCompress);
        //二维码中间加图片
        ByteArrayOutputStream out2 = QRCodeUtil.encodeIO(content, imgFile.getPath(), needCompress);


        //返回二维码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("image/jpeg;charset=UTF-8");
        response.setContentLength(out.size());
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(out.toByteArray());
        outputStream.flush();
        outputStream.close();
    }

    private String getInviteCodeByUserId(String userid) {
    
    
        return "ANGYS1";
    }


}
package com.biturd.manghejava.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.awt.SunHints;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// https://uutool.cn/img-coord/
// https://blog.csdn.net/qq_38377774/article/details/108767573
// https://blog.csdn.net/weixin_39220472/article/details/120888956?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0.pc_relevant_default&spm=1001.2101.3001.4242.1&utm_relevant_index=3
public class QRCodeUtil {
    
    
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int WIDTH = 80;
    // LOGO高度
    private static final int HEIGHT = 80;
    // LOGO宽度
    private static final int LEFT = 225;
    // LOGO高度
    private static final int UP = 475;
    // 288 535

    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
    
    
        Map<EncodeHintType, Object> hints = new ConcurrentHashMap();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
    
    
            for (int y = 0; y < height; y++) {
    
    
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null || "".equals(imgPath)) {
    
    
            return image;
        }
        // 插入图片
        QRCodeUtil.insertImage(image, imgPath, needCompress);
        return image;
    }

    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
    
    

        File file = new File(imgPath);
        if (!file.exists()) {
    
    
            System.err.println("" + imgPath + "   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) {
    
     // 压缩LOGO
            if (width > WIDTH) {
    
    
                width = WIDTH;
            }
            if (height > HEIGHT) {
    
    
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
    
    
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        mkdirs(destPath);
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }

    public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
    
    
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        return image;
    }

    public static void mkdirs(String destPath) {
    
    
        File file = new File(destPath);
        // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
    
    
            file.mkdirs();
        }
    }

    public static void encode(String content, String imgPath, String destPath) throws Exception {
    
    
        QRCodeUtil.encode(content, imgPath, destPath, false);

    }

    public static byte[] getQRCodeImage(String content) throws WriterException, IOException {
    
    
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE);
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, FORMAT_NAME, pngOutputStream);
        byte[] pngData = pngOutputStream.toByteArray();
        return pngData;
    }

    public static void encode(String content, String destPath) throws Exception {
    
    
        QRCodeUtil.encode(content, null, destPath, false);
    }

    public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
            throws Exception {
    
    
        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    public static void encode(String content, OutputStream output) throws Exception {
    
    
        QRCodeUtil.encode(content, null, output, false);
    }

    public static String decode(File file) throws Exception {
    
    
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
    
    
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    public static String decode(String path) throws Exception {
    
    
        return QRCodeUtil.decode(new File(path));
    }

    //二维码中间有图片
    public static ByteArrayOutputStream encodeIO(String content, String imgPath, Boolean needCompress) throws Exception {
    
    
        BufferedImage image = QRCodeUtil.createImage(content, imgPath,
                needCompress);
        //创建储存图片二进制流的输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //将二进制数据写入ByteArrayOutputStream
        ImageIO.write(image, "jpg", baos);
        return baos;
    }

    private static BufferedImage createFromImage(String content, BufferedImage outer, boolean needCompress) throws Exception {
    
    
        Map<EncodeHintType, Object> hints = new ConcurrentHashMap();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
    
    
            for (int y = 0; y < height; y++) {
    
    
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        // 插入图片
        QRCodeUtil.insertFromImage(outer, image, needCompress);
        return outer;
    }

    private static void insertFromImage(BufferedImage src,BufferedImage qrCode,  boolean needCompress) throws Exception {
    
    
        Image image = null;
        int width = qrCode.getWidth(null);
        int height = qrCode.getHeight(null);
        if (needCompress) {
    
     // 压缩LOGO
            if (width > WIDTH) {
    
    
                width = WIDTH;
            }
            if (height > HEIGHT) {
    
    
                height = HEIGHT;
            }
            image = qrCode.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
        }//左上 256 500  右下 290 535
        // 插入LOGO
        Graphics2D graph = src.createGraphics();
        graph.drawImage(image, LEFT, UP, null);
        graph.setColor(Color.WHITE);
        graph.dispose();
    }

//


    //图片中间有二维码
    public static ByteArrayOutputStream encodeIOWith(String content, BufferedImage outer, Boolean needCompress) throws Exception {
    
    
        BufferedImage image = QRCodeUtil.createFromImage(content, outer,
                needCompress);
        addText(image, content);

        //创建储存图片二进制流的输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //将二进制数据写入ByteArrayOutputStream
        ImageIO.write(image, "jpg", baos);
        return baos;
    }
    public static void addText(BufferedImage image,String text){
    
    
        Graphics2D graph = image.createGraphics();
//        graph.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        // 5、设置水印文字颜色
        graph.setColor(Color.black);
        graph.setFont(new Font("宋体", Font.BOLD, 15));
        // 文字增加清晰度
        graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
        graph.drawString("邀请码:", 240, 450);
        graph.drawString(text, 220, 470);

        graph.dispose();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42873554/article/details/124557160