根据url生成二维码图片并上传到文件系统中

根据url生成二维码图片并上传到文件系统中

首先生成二维码,因为最后要上传到文件系统中 调用restTemplate,所以返回ByteArrayResource

1.参数url : 要生成url 的链接
2.words :生成的二维码下面添加的文字 可以没有
3.定义两个成员变量,生成二维码是黑白色

 private static final int BLACK = 0xFF000000;
 private static final int WHITE = 0xFFFFFFFF;
public static ByteArrayResource createQrCode(String url,String words) {
        try {
            Map<EncodeHintType, String> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
            //=======================生成文件 可以放在本地======================
            //File file = new File(path, fileName);
            //if (file.exists() || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile())) {
            //   writeToFile(bitMatrix, "jpg", file);
            //    System.out.println("搞定:" + file);
            //}
           //=============此处生成流因为后面要上传到文件系统中,所以直接通过流上传===========
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            writeToStream(bitMatrix, "jpg", outputStream,words);
            //==============生成输入流========================
            //ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            ByteArrayResource arrayResource = new ByteArrayResource(outputStream.toByteArray()){
                @Override
                public String getFilename() throws IllegalStateException {
                    return System.currentTimeMillis()+"";
                }
            };
            return arrayResource;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

根据自己要生成的结果 自行选择调用哪个方法

static void writeToFile(BitMatrix matrix, String format, File file,String words) throws IOException {
        BufferedImage image = toBufferedImage(matrix, words);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    static void writeToStream(BitMatrix matrix, String format, OutputStream stream,String words) throws IOException {
        BufferedImage image = toBufferedImage(matrix, words);
        if (!ImageIO.write(image, format, stream)) {
            throw new IOException("Could not write an image of format " + format);
        }
    }
private static BufferedImage toBufferedImage(BitMatrix matrix, String words) {
        int width = matrix.getWidth();
        int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        Graphics2D outg = image.createGraphics();
        setGraphics2D(outg);
        // 画二维码到新的面板
        outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
        // 画文字到新的面板
        //Color color=new Color(183,183,183);
        outg.setColor(Color.BLACK);
        // 字体、字型、字号
        outg.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        //文字长度
        int strWidth = outg.getFontMetrics().stringWidth(words);
        //总长度减去文字长度的一半  (居中显示)
        int wordStartX=(width - strWidth) / 2;
        //height + (outImage.getHeight() - height) / 2 + 12
        int wordStartY=height-20;
        // 画文字
        outg.drawString(words, wordStartX, wordStartY);
        outg.dispose();
        image.flush();
        return image;
    }
private static void setGraphics2D(Graphics2D graphics2D){
        graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        graphics2D.setStroke(s);
    }

这样加文字的二维码的工具类就生成了

业务层的代码
//这是要生成二维码的url
String url = "http://www.baidu.com";
//要添加到二维码下面的文字
String words = "我的二维码";
//调用刚才的工具类
ByteArrayResource qrCode = QRcodeUtil.createQrCode(h5Url,words);
//将生成的ByteArrayResource 封装到MultiValueMap中
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file",qrCode);
// 然后用restTemplate 调用你的文件系统服务进行上传就可以啦
需要注意

1.文件系统那边用MultipartFile接收即可
2.在文件系统那边 设置二维码的后缀jpg或者png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值