QRCode生成二維碼java
pom文件中引入jar:net.glxn.qrgen.javase.jarspring
<!--二維碼依賴-->
<dependency>
<groupId>net.glxn.qrgen</groupId>
<artifactId>javase</artifactId>
<version>2.0</version>
</dependency>
複製代碼
2種測試:mongodb
package com.dist.QRCode;
import com.dist.base.BaseTest;
import net.glxn.qrgen.core.AbstractQRCode;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.core.vcard.VCard;
import net.glxn.qrgen.javase.QRCode;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
/** * 引入jar:net.glxn.qrgen.javase * * @program: springbootdemo * @Date: 2019/1/25 9:01 * @Author: Mr.Zheng * @Description: */
public class QRCodeTest{
/** * 二維碼生成測試1 */
@Test
public void testQrcode1() {
AbstractQRCode qrCode = QRCode.from("https://www.baidu.com");
// 設置字符集,支持中文
qrCode.withCharset("utf-8");
// 設置生成的二維碼圖片大小
qrCode.withSize(260,260);
ByteArrayOutputStream out = qrCode.to(ImageType.PNG).stream();
File file = new File("D:\\qrCode.png");
FileOutputStream fout = null;
try {
fout = new FileOutputStream(file);
fout.write(out.toByteArray());
fout.flush();
System.out.println("***********二維碼生成成功!**********");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fout.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/** * 二維碼生成測試2 */
@Test
public void testQrcode2() {
ByteArrayOutputStream bout =
QRCode.from("https://www.baidu.com")
.withCharset("utf-8")
.withSize(250, 250)
.to(ImageType.PNG)
.stream();
try {
OutputStream out = new FileOutputStream("D:\\qr-code.png");
bout.writeTo(out);
out.flush();
out.close();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/** * 推薦使用:模板 * 二維碼生成測試3 :VCard是標準電子商務名片格式,包含元數據有,名稱,地址,公司,手機號,職位,郵箱,網站等 */
@Test
public void testQrcode3() {
VCard vCard = new VCard();
vCard.setName("張三");
vCard.setAddress("上海市浦東新區張江鎮");
vCard.setCompany("公司名稱");
vCard.setPhoneNumber("15937966356");
vCard.setTitle("Java開發");
vCard.setEmail("126354652@qq.com");
vCard.setWebsite("https://www.jianshu.com/u/70d69269bd09");
ByteArrayOutputStream bout =
QRCode.from(vCard)
.withCharset("utf-8")
.withSize(250, 250)
.to(ImageType.PNG)
.stream();
try {
OutputStream out = new FileOutputStream("D:\\qr-code-vcard.png");
bout.writeTo(out);
out.flush();
out.close();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
複製代碼
以上爲測試,想要用到項目種須要作更改。數據庫
更改:springboot
存儲位置:能夠是本地路徑,或者存到mongodb,或數據庫等測試
存儲內容:url/String/對象VCard網站
生成形式:能夠是文件/流編碼
類型:ImageType:JPG, GIF, PNG, BMPurl
大小:withSize 自定義spa
支持中文:withCharset("utf-8")
編碼規範:適用於本身的項目(此實例只是測試使用)