java 生成简单二维码(二)

java 生成简单二维码(二)



前言

产品说你上次已经生成二维码,能不能再二维码下面加文字,便于提示用户,我……,开整吧。


一、怎么加文字

二维码已经是图片了,那么通过画布来进行添加,应该是可以行的。

二、使用步骤

1.引入坐标

请移步到:java生成二维码(一)

2.编写生成二维码类

代码如下(示例):

package demo;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class QRCodeGenerator {

    // 二维码宽高
    private static final int QRWIDTH = 180;
    private static final int QRHEIGHT = 180;

    private static final int BGWIDTH = 180;
    private static final int BGHEIGHT = 200;

    public static BufferedImage getQRCode(byte[] img){
        try {
            ByteArrayInputStream in = new ByteArrayInputStream(img);    //将b作为输入流;
            return ImageIO.read(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *@param image 表示获得的BufferedImage
     *@param words 文本集合
     */
    public static BufferedImage insertWords(BufferedImage image, java.util.List<String> words) {
        // 新的图片,把带logo的二维码下面加上文字
        if (words.size() > 0) {
            BufferedImage outImage = new BufferedImage(BGWIDTH, BGHEIGHT, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = outImage.createGraphics();
            // 抗锯齿
            setGraphics2D(g2d);
            // 设置白色
            setColorWhite(g2d);
            // 画条形码到新的面板
            System.out.println(image.getWidth());
            System.out.println(image.getHeight());
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color = new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(new Font("宋体", Font.PLAIN, 12));
            //文字长度
            int wordStartY = BGHEIGHT - (words.size() * 12);
            for(String word : words) {
                int strWidth = g2d.getFontMetrics().stringWidth(word);
                int wordStartX = (BGWIDTH - strWidth) / 2;
                // 画文字
                g2d.drawString(word, wordStartX, wordStartY);
                wordStartY += 18;
            }
            g2d.dispose();
            outImage.flush();
            return outImage;
        }
        return null;
    }


    /**
     * 设置 Graphics2D 属性  (抗锯齿)
     * @param g2d  Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d){
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }

    /**
     * 设置背景为白色
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setColorWhite(Graphics2D g2d){
        g2d.setColor(Color.WHITE);
        //填充整个屏幕
        g2d.fillRect(0,0, BGWIDTH, BGHEIGHT);
        //设置笔刷
        g2d.setColor(Color.BLACK);
    }


    /**
     * 生成二维码
     * @param text 二维码的内容
     * @param width 宽度
     * @param height 高度
     */
    public static byte[] generateQRCodeImage(String text, int width, int height)throws WriterException, IOException {
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        BitMatrix bitMatrix = null;
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  pngOutputStream.toByteArray();
    }

    
    public static void main(String[] args) throws IOException, WriterException {
        java.util.List<String> str = new ArrayList<>();
        str.add("SN:1234567890");
        str.add("领一国际");

        byte[] bytes = generateQRCodeImage("1234567890", QRWIDTH, QRHEIGHT);
        BufferedImage image = insertWords(getQRCode(bytes), str);

        File outputfile = new File("./1.png");
        ImageIO.write(image, "png", outputfile);
    }


}

注意
二维码生成是自带了边距,所以QRWIDTHQRHEIGHTBGWIDTH的值一般情况下保存一致。

字体大小以及行距,字体高度,需要自己手动调节


测试结果

这里就不贴图了,原因你们懂的……。

总结

以上就是今天要讲的内容,本文仅仅原来基础上进行介绍和使用,而生成的二维码很好用。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值