生成带logo的二维码

一,生成带log的二维码

  1)生成的二维码是流返回,或者是直接写到指定文件夹

二,准备资料

  1)引入jar包

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
    <!-- 二维码生成器 -->
    <dependency>
        <groupId>com.google.zxing</groupId>
        <artifactId>core</artifactId>
        <version>3.3.0</version>
    </dependency>

  2)引入工具类

    1.直接使用


import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import com.google.zxing.common.BitMatrix;

public class MatrixToImageWriter {
    private static final int BLACK = 0xFF000000;
       private static final int WHITE = 0xFFFFFFFF;
     
       private MatrixToImageWriter() {}
     
       
       public static BufferedImage toBufferedImage(BitMatrix matrix) {
         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);
           }
         }
         return image;
       }
     
       
       public static void writeToFile(BitMatrix matrix, String format, File file) //生成文件方法
           throws IOException {
         BufferedImage image = toBufferedImage(matrix);
         if (!ImageIO.write(image, format, file)) {
           throw new IOException("Could not write an image of format " + format + " to " + file);
         }
       }
     
       
       public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)//生成流的方法
           throws IOException {
         BufferedImage image = toBufferedImage(matrix);
         //调用log生成工具,如果不需要logo就不调用改工具类
         LogoConfig logoConfig = new LogoConfig();
          image = logoConfig.LogoMatrix(image);
         if (!ImageIO.write(image, format, stream)) {
           throw new IOException("Could not write an image of format " + format);
         }
       }
}

    2)logo工具类


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class LogoConfig {
     
    public BufferedImage LogoMatrix(BufferedImage matrixImage)  
            throws IOException {  
        /** 
         * 读取二维码图片,并构建绘图对象 
         */  
        Graphics2D g2 = matrixImage.createGraphics();  
  
        int matrixWidth = matrixImage.getWidth();  
        int matrixHeigh = matrixImage.getHeight();  
  
        //获取logo,这里可以使用本地文件,也可以由外部传入 
        BufferedImage logo = ImageIO.read(new File("F:/图片资料/20110711104956189.jpg"));  
        
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        // 开始绘制图片  
        g2.drawImage(logo, 125, 125,  //这里的125,125决定了logo与上下边距,左右边距的距离
                matrixWidth / 6, matrixHeigh / 6, null);// 这里的的/6决定了logo图片的大小
        BasicStroke stroke = new BasicStroke(5, BasicStroke.CAP_ROUND,  
                BasicStroke.JOIN_ROUND);  
        g2.setStroke(stroke);// 设置笔画对象  
        // 指定弧度的圆角矩形  
        RoundRectangle2D.Float round = new RoundRectangle2D.Float(  
                125, 125, matrixWidth / 6,  
                matrixHeigh / 6, 4, 4); ///6这里决定了圆角矩形的大小,4代表矩形边框的宽度
        g2.setColor(Color.white);  
        g2.draw(round);// 绘制圆弧矩形  
  
        g2.dispose();  
        matrixImage.flush();  
        return matrixImage;  
    }  
}

三,调用

  @Controller

public class QRcode {
    
    @RequestMapping("getQrcode") 
    public void getQrcode(String contents,HttpServletRequest request,HttpServletResponse response) {
        BitMatrix bitMatrix =null;
     //解决get乱码问题,没有乱码可以忽略
     //
contents传入的是要生成二维码的内容


String conten = null;
        try {
             conten = new String(contents.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        //准备参数二维码的大小
        int width=300;
        int height=300;
        //配置参数
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)  ,这个等级根据logo图片的大小来定,参考logo大小占二维码的比例
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); 
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            bitMatrix = multiFormatWriter.encode(conten, BarcodeFormat.QR_CODE, width, height,hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        
        ServletOutputStream outputStream = null;
        try {
        //获取流 outputStream = response.getOutputStream(); } catch (IOException e1) { e1.printStackTrace(); } //File file = new File("F:/test","test.jpg"); try {
        //调用返回流的方法 MatrixToImageWriter.writeToStream(bitMatrix, "jpg", outputStream); } catch (IOException e) { e.printStackTrace(); } } }

四,简单页面示例

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>二维码测试</title>
</head>
<body>
    
    <img alt="" id="myimg">
    <input type="text" id="im"/>
    <input type="button" id="but" value="获取二维码">
    <script type="text/javascript" src="jquery-easyui-1.5.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("#but").click(function(){
            var text=$("#im").val();
            $("#myimg").attr("src","getQrcode?contents="+text)
        })
    </script>
</body>
</html>

 

五,效果展示

        1)点击获取                                              

 

        2)返回内容

 

posted @ 2017-12-08 20:41  言_曦  阅读(1877)  评论(0编辑  收藏  举报