最近因?yàn)橐恍┕ぷ餍枰枰鶕?jù)實(shí)際的信息生成QR-Code二維碼圖片文件,自然想到zxing庫(kù)了,具體的代碼很簡(jiǎn)單,做個(gè)備忘。
首先是引入zxing庫(kù),我是使用maven構(gòu)建項(xiàng)目的,添加依賴:
1
2
3
4
5
|
< dependency > < groupId >com.google.zxing</ groupId > < artifactId >javase</ artifactId > < version >3.3.0</ version > </ dependency > |
然后是測(cè)試樣列代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; /** * 使用zxing庫(kù)生成QRCode二維碼樣例程序 * * @author 阿信sxq * */ public class QrcodeDemo { public static void main(String[] args) { new QrcodeDemo().genQrcode( "https://my.oschina.net/songxinqiang" ); } public void genQrcode(String message) { //輸出目標(biāo)文件 File file = new File( "E:\\qrcode.png" ); if (!file.exists()) { try { file.mkdirs(); file.createNewFile(); } catch (IOException e) {} } //設(shè)置參數(shù),輸出文件 Map<EncodeHintType, String> hints = new HashMap<>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8" ); try { BitMatrix bitMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, 300 , 300 , hints); // 生成矩陣 MatrixToImageWriter.writeToPath(bitMatrix, "png" , file.toPath()); // 輸出圖像 } catch (Exception e) {} } } |
這里是為了做演示,內(nèi)容直接生成的我空間的地址,并且目標(biāo)文件也是現(xiàn)在家里使用的windows 的文件位置,在具體實(shí)際的使用中需要具體修改。
生成的圖片是:
(調(diào)整過(guò)大小)
在這里需要說(shuō)明的是,二維碼中的點(diǎn)的大小會(huì)隨二維碼文字內(nèi)容的多少自動(dòng)變化,所以在文字內(nèi)容很多的時(shí)候需要把圖片的尺寸調(diào)大,否則點(diǎn)太小了,一般的手機(jī)掃描起來(lái)很吃力
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
原文鏈接:https://my.oschina.net/songxinqiang/blog/885565