1. 程式人生 > >生成帶logo的二維碼

生成帶logo的二維碼

二維 qrc row ack {} trac zxing req onf

一,生成帶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)返回內容

技術分享圖片

生成帶logo的二維碼