java 简单快速的生成二维码(带图片)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36481052/article/details/78922725
**使用java+zxing 简单快速的生成二维码。**

效果图:
生成的二维码

首先需要引入两个jar文件:

    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.8</version>
    </dependency>
    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>javase</artifactId>
      <version>3.0.0</version>
    </dependency>

下面就是生成二维码的工具类:

    public class CreatrQrCode{
    // logo默认边框颜色
    public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;
    // logo默认边框宽度
    public static final int DEFAULT_BORDER = 1;
    // logo大小默认为照片的1/6
    public static final int DEFAULT_LOGOPART = 6;

    private final int border = DEFAULT_BORDER;
    private final Color borderColor;
    private final int logoPart;

    /**
     * Creates a default config with on color {@link #BLACK} and off color
     * {@link #WHITE}, generating normal black-on-white barcodes.
     */
    public CreatrQrCode() {
        this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);
    }

    public demo02(Color borderColor, int logoPart) {
        this.borderColor = borderColor;
        this.logoPart = logoPart;
    }

    public Color getBorderColor() {
        return borderColor;
    }

    public int getBorder() {
        return border;
    }

    public int getLogoPart() {
        return logoPart;
    }

    /**
     * 给二维码图片添加Logo
     *
     * @param qrPic
     * @param logoPic
     */
    public static void addLogo_QRCode(File qrPic, File logoPic, CreatrQrCode logoConfig) {
        try {
            if (!qrPic.isFile() || !logoPic.isFile()) {
                System.out.print("file not find !");
                System.exit(0);
            }

            /**
             * 读取二维码图片,并构建绘图对象
             */
            BufferedImage image = ImageIO.read(qrPic);
            Graphics2D g = image.createGraphics();

            /**
             * 读取Logo图片
             */
            BufferedImage logo = ImageIO.read(logoPic);

            int widthLogo = image.getWidth() / logoConfig.getLogoPart();
            //    int    heightLogo = image.getHeight()/logoConfig.getLogoPart();
            int heightLogo = image.getWidth() / logoConfig.getLogoPart(); //保持二维码是正方形的

            // 计算图片放置位置
            int x = (image.getWidth() - widthLogo) / 2;
            int y = (image.getHeight() - heightLogo) / 2;


            //开始绘制图片
            g.drawImage(logo, x, y, widthLogo, heightLogo, null);
            g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
            g.setStroke(new BasicStroke(logoConfig.getBorder()));
            g.setColor(logoConfig.getBorderColor());
            g.drawRect(x, y, widthLogo, heightLogo);

            g.dispose();

            ImageIO.write(image, "jpeg", new File("D:/ceshi/789.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param pressText 文字
     * @param newImg    带文字的图片
     * @param targetImg 需要添加文字的图片
     * @param fontStyle
     * @param color
     * @param fontSize
     * @param width
     * @param height
     * @为图片添加文字
     */
    public static void pressText(String pressText, String newImg, String targetImg, int fontStyle, Color color, int fontSize, int width, int height) {

        //计算文字开始的位置
        //x开始的位置:(图片宽度-字体大小*字的个数)/2
        int startX = (width - (fontSize * pressText.length())) / 2;
        //y开始的位置:图片高度-(图片高度-图片宽度)/2
        int startY = height - (height - width) / 2;

        try {
public class CreatrQrCode {
    // logo默认边框颜色
    public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;
    // logo默认边框宽度
    public static final int DEFAULT_BORDER = 1;
    // logo大小默认为照片的1/6
    public static final int DEFAULT_LOGOPART = 6;

    private final int border = DEFAULT_BORDER;
    private final Color borderColor;
    private final int logoPart;

    /**
     * Creates a default config with on color {@link #BLACK} and off color
     * {@link #WHITE}, generating normal black-on-white barcodes.
     * 在颜色{@ link #黑}和颜色上创建一个默认配置
     *  {@link # WHITE},生成正常的黑白条码。
     */
    public CreatrQrCode() {
        this(DEFAULT_BORDERCOLOR, DEFAULT_LOGOPART);
    }

    public CreatrQrCode(Color borderColor, int logoPart) {
        this.borderColor = borderColor;
        this.logoPart = logoPart;
    }

    public Color getBorderColor() {
        return borderColor;
    }

    public int getBorder() {
        return border;
    }

    public int getLogoPart() {
        return logoPart;
    }

    /**
     * 给二维码图片添加Logo
     *
     * @param qrPic
     * @param logoPic
     */
    public static void addLogo_QRCode(File qrPic, File logoPic, CreatrQrCode creatrQrCode) {
        try {
            if (!qrPic.isFile() || !logoPic.isFile()) {
                System.out.print("file not find !");
                System.exit(0);
            }

            /**
             * 读取二维码图片,并构建绘图对象
             */
            BufferedImage image = ImageIO.read(qrPic);
            Graphics2D g = image.createGraphics();

            /**
             * 读取Logo图片
             */
            BufferedImage logo = ImageIO.read(logoPic);

            int widthLogo = image.getWidth() / creatrQrCode.getLogoPart();
            //    int    heightLogo = image.getHeight()/logoConfig.getLogoPart();
            int heightLogo = image.getWidth() / creatrQrCode.getLogoPart(); //保持二维码是正方形的

            // 计算图片放置位置
            int x = (image.getWidth() - widthLogo) / 2;
            int y = (image.getHeight() - heightLogo) / 2;


            //开始绘制图片
            g.drawImage(logo, x, y, widthLogo, heightLogo, null);
            g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
            g.setStroke(new BasicStroke(creatrQrCode.getBorder()));
            g.setColor(creatrQrCode.getBorderColor());
            g.drawRect(x, y, widthLogo, heightLogo);

            g.dispose();

            ImageIO.write(image, "jpeg", new File("D:/ceshi/789.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param pressText 文字
     * @param newImg    带文字的图片
     * @param targetImg 需要添加文字的图片
     * @param fontStyle
     * @param color
     * @param fontSize
     * @param width
     * @param height
     * @为图片添加文字
     */
    public static void pressText(String pressText, String newImg, String targetImg, int fontStyle, Color color, int fontSize, int width, int height) {

        //计算文字开始的位置
        //x开始的位置:(图片宽度-字体大小*字的个数)/2
        int startX = (width - (fontSize * pressText.length())) / 300;
        //y开始的位置:图片高度-(图片高度-图片宽度)/2
        int startY = height - (height - width) / 3;

        try {
            File file = new File(targetImg);
            Image src = ImageIO.read(file);
            int imageW = src.getWidth(null);
            int imageH = src.getHeight(null);
            BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.createGraphics();
            g.drawImage(src, 0, 0, imageW, imageH, null);
            g.setColor(color);
            g.setFont(new Font(null, fontStyle, fontSize));
            g.drawString(pressText, startX, startY);
            g.dispose();

            FileOutputStream out = new FileOutputStream(newImg);
            ImageIO.write(image, "JPEG", out);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();
            System.out.println("image press success");
        } catch (Exception e) {
            System.out.println(e);
        }
    }
 }

在主函数中测试一下我们的的工具类有没有问题:

 public static void main(String args[]) {
        try {
            //二维码表示的内容
            String content = "http://www.baidu.com";

            //存放logo的文件夹
            String path = "D:/ceshi/";

            MultiFormatWriter
                    multiFormatWriter = new MultiFormatWriter();

            @SuppressWarnings("rawtypes")
            Map hints = new HashMap();

            //设置UTF-8, 防止中文乱码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //设置二维码四周白色区域的大小
            hints.put(EncodeHintType.MARGIN,0);
            //设置二维码的容错性
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            //width:图片完整的宽;height:图片完整的高
            //因为要在二维码下方附上文字,所以把图片设置为长方形(高大于宽)
            int width = 400;
            int height = 460;

            //画二维码,记得调用multiFormatWriter.encode()时最后要带上hints参数,不然上面设置无效
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

            //qrcFile用来存放生成的二维码图片(无logo,无文字)
            File qrcFile = new File(path,"wutu.jpg");

            //logoFile准备放在二维码中的图片(path:图片路径,图片名称)
            File logoFile = new File(path,"shilinwei.jpg");

            //开始画二维码
            MatrixToImageWriter.writeToFile(bitMatrix, "jpg", qrcFile);

            //在二维码中加入图片
            CreatrQrCode creatrQrCode = new CreatrQrCode(); //LogoConfig中设置Logo的属性
            addLogo_QRCode(qrcFile, logoFile, creatrQrCode);


            int font = 20; //字体大小
            int fontStyle = 4; //字体风格

            //用来存放的带有logo+文字的二维码图片
            String newImageWithText = "D:/ceshi/456.jpg";
            //带有logo二维码图片
            String targetImage = "D:/ceshi/789.png";
            //附加在图片上的文字信息
            String text = "my name is Shi Linwei";

            //在二维码下方添加文字(文字居中)
            pressText(text, newImageWithText, targetImage, fontStyle, Color.red, font,  width,  height) ;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

我运行后的所有图片文件:
这里写图片描述

完事了,路过的大神请多多指点,谢谢

猜你喜欢

转载自blog.csdn.net/qq_36481052/article/details/78922725