今天在公司,完成了之前的任務,沒有什么事做,就想鼓搗一下二維碼,因為之前沒有接觸過,我就去翻看了幾本書,也基本完成了二維碼的實現,以及添加二維碼的LOGO。
現在繪制二維碼一般都使用的是谷歌的zxing的一個核心包,鏈接:https://pan.baidu.com/s/1eSB5tlg 密碼:e7eg
好了,不多說了,直接上代碼!
首先是我們一個工具類的編寫,用於生成二維碼,和添加LOGO
1 package com.warrenwell.Test; 2 3 import java.awt.Graphics; 4 import java.awt.Image; 5 import java.awt.image.BufferedImage; 6 import java.io.File; 7 import java.io.IOException; 8 9 import javax.imageio.ImageIO; 10 11 import com.google.zxing.common.BitMatrix; 12 13 public final class MatrixWriteToImage { 14 private static final int BLACK=0XFF000000; 15 private static final int WHITE=0XFFFFFFFF; 16 private MatrixWriteToImage(){ 17 18 } 19 public static BufferedImage toBufferedImage(BitMatrix matrix){ 20 BufferedImage bi=new BufferedImage(matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_RGB); 21 for(int i=0;i<matrix.getWidth();i++){ 22 for(int j=0;j<matrix.getHeight();j++){ 23 //有值的是黑色,沒有值是白色 24 bi.setRGB(i, j,matrix.get(i, j)?BLACK:WHITE); 25 } 26 } 27 return bi; 28 } 29 public static void MatrixToImage(BitMatrix matrix,String format,File f) throws IOException{ 30 //將我們的logo提取出來,建議這里單獨寫一個方法,我只是為了方便 31 BufferedImage b=ImageIO.read(new File("e:/1.jpg")); 32 //將logo弄成70*70,如果想大點,記得要提高我們二維碼的容錯率 33 Image image=b.getScaledInstance(70, 70,Image.SCALE_FAST); 34 BufferedImage bi=toBufferedImage(matrix); 35 //獲取二維碼畫刷 36 Graphics g=bi.getGraphics(); 37 //定位 38 g.drawImage(image ,250,150,null); 39 //二維碼畫到相應文件位置,結束。 40 if(ImageIO.write(bi, format, f)){ 41 42 } 43 System.out.println("成功!"); 44 } 45 }
之后就在我們的主要的函數中進行調用:
1 package com.warrenwell.Test; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.HashMap; 6 7 import com.google.zxing.BarcodeFormat; 8 import com.google.zxing.EncodeHintType; 9 import com.google.zxing.MultiFormatWriter; 10 import com.google.zxing.WriterException; 11 import com.google.zxing.common.BitMatrix; 12 13 public class ErweiMa { 14 public static void main(String[] args) throws WriterException, IOException { 15 MultiFormatWriter mulwriter=new MultiFormatWriter(); 16 //寫入二維碼的內容,也可以是鏈接,xml,json字符串 17 String content="qwqwQAQ"; 18 //對EncodeHintType的各種設置寫入一個map中 19 HashMap<EncodeHintType, Object> hints=new HashMap<>(); 20 //設置我們放入的字符串編碼為utf-8 21 hints.put(EncodeHintType.CHARACTER_SET,"utf-8"); 22 //長寬,二維碼為QR碼 23 BitMatrix bitmatrix=mulwriter.encode(content,BarcodeFormat.QR_CODE, 400,400,hints); 24 //調用MatrixWriteToImage的方法 25 MatrixWriteToImage.MatrixToImage(bitmatrix,"png",new File("f:/1.png")); 26 } 27 }
最后我們的二維碼就會在我們的F盤中出現了,大家可以也去試試呢。
關於修改我們的二維碼的容錯率也是通過寫入我們的Line19的hashmap中進行修改,只需要添加一行,將我們的容錯率級別提高,那么你的LOGO就可以大一點了。
1 hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);
本人在蘇州做軟件開發一年多,希望能夠和大家一起學習,計算機一直是我的興趣愛好,這是我第一篇博客,是今天無聊的一時興起,不過也會堅持下去。