网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

java中怎么实现生成二维码

java中怎么实现生成二维码,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

在余姚等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供成都网站设计、做网站 网站设计制作按需搭建网站,公司网站建设,企业网站建设,成都品牌网站建设,营销型网站,成都外贸网站建设,余姚网站建设费用合理。

如果是maven项目要在项目中添加依赖

   com.google.zxing
   javase
   3.3.0
package com.aigyun.config;


import com.aigyun.constant.StringUtils;
import com.aigyun.entity.DeviceUavInfo;
import com.alibaba.fastjson.JSONObject;
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.decoder.ErrorCorrectionLevel;
import com.swetake.util.Qrcode;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

public class QCodeUtil {

    private static final int QRCOLOR = 0xFF000000; // 默认是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色


    // 用于设置QR二维码参数
    private static Map hints = new HashMap() {
        private static final long serialVersionUID = 1L;

        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
            put(EncodeHintType.MARGIN, 0);
        }
    };

    /**
     * java绘制只包含内容的二维码
     *
     * @param content
     * @param imgPath
     */
    public static void getQrCodeImg(String content, String imgPath) {
        int width = 300;
        int height = 300;

        Qrcode qrcode = new Qrcode();
        qrcode.setQrcodeErrorCorrect('M');  // 设置纠错级别(级别有:L(7%) M(15%) Q(25%) H(30%) )
        qrcode.setQrcodeEncodeMode('B'); // 设置编码方式
        qrcode.setQrcodeVersion(7); // 设置二维码版本(版本有 1-40个,)

        // 1.设置图片大小(BufferedImage.TYPE_INT_RGB:利用三原色绘制二维码)
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D gs = img.createGraphics(); // 创建画笔
        gs.setBackground(Color.WHITE); // 设置背景为白色
        gs.clearRect(0, 0, width, height);  // 设置一个矩形(四个参数分别为:开始绘图的x坐标,y坐标,图片宽,图片高)
        gs.setColor(Color.BLACK); // 设置二维码图片的颜色
        byte[] bt = null; // 把内容转换字节数组
        try {
            bt = content.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        int py = 4; // 偏移量
        boolean[][] code = qrcode.calQrcode(bt); // 开始准备画图
        for (int i = 0; i < code.length; i++) {
            for (int j = 0; j < code[i].length; j++) {
                if (code[j][i]) {
                    // 四个参数(画图的起始x和y位置,每个小模块的宽和高(二维码是有一个一个的小模块构成的));
                    gs.fillRect(j * 6 + py, i * 6 + py, 6, 6);
                }
            }
        }
        // 画图
        try {
            ImageIO.write(img, "png", new File(imgPath));
            System.out.println("OK!");
        } catch (IOException e) {
            System.out.println("二维码异常。。。。。");
            e.printStackTrace();
        }
    }

    public static String decode(String filepath) {
        try {
            BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
            LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            HashMap decodeHints = new HashMap();
            decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(bitmap, decodeHints);
            return result.getText();
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * zxing生成带logo的二维码
     *
     * @param logoFile
     * @param codeFile
     * @param qrUrl
     * @param note
     */
    public static boolean drawLogoQRCode(final File logoFile, File codeFile, final String qrUrl, final String note, final int width, final int height) {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bm = null;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        ;
        try {
            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException we) {
            we.printStackTrace();
            return false;
        }

        // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
            }
        }

        //绘制图片
        Graphics2D g = image.createGraphics();
        try {
            BufferedImage logo = ImageIO.read(logoFile);
            g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
            g.dispose();
            logo.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        // 自定义文本描述
        if (StringUtils.isNotEmpty(note)) {
            // 新的图片,把带logo的二维码下面加上文字
            BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D outg = outImage.createGraphics();
            // 画二维码到新的面板
            outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            outg.setColor(Color.BLACK);
            outg.setFont(new Font("楷体", Font.BOLD, 30)); // 字体、字型、字号
            int strWidth = outg.getFontMetrics().stringWidth(note);
            if (strWidth > 399) {
                //长度过长就截取前面部分
                // 长度过长就换行
                String note1 = note.substring(0, note.length() / 2);
                String note2 = note.substring(note.length() / 2, note.length());
                int strWidth2 = outg.getFontMetrics().stringWidth(note1);
                int strWidth3 = outg.getFontMetrics().stringWidth(note2);
                outg.drawString(note1, 200 - strWidth2 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg2 = outImage2.createGraphics();
                outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                outg2.setColor(Color.BLACK);
                outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
                outg2.drawString(note2, 200 - strWidth3 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                outg2.dispose();
                outImage2.flush();
                outImage = outImage2;
            } else {
                outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 画文字
            }
            outg.dispose();
            outImage.flush();
            image = outImage;
        }

        image.flush();

        try {
            ImageIO.write(image, "png", codeFile); // TODO
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }


    public static void main(String[] args) {

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("reg_id", 12123);
//        getQrCodeImg(jsonObject.toJSONString(), "f:/qrcode/test1.jpg");
//        //encode(jsonObject.toJSONString(), "f:/qrcode/test.jpg");
//        File logoFile = new File("f:/qrcode/512x512bb.jpg");
//        File codeFile = new File("f:/qrcode/test.png");
//        drawLogoQRCode(logoFile, codeFile, jsonObject.toJSONString(),"扫一扫查看配置参数");
//
//        String content = decode("f:/qrcode/test.jpg");
//        System.out.println(content);



        System.out.println(UUID.randomUUID().toString());
    }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。


文章题目:java中怎么实现生成二维码
网址分享:http://bjjierui.cn/article/pegjcs.html

其他资讯