Java生成與解析二維碼的完整指南
前言
二維碼是一種能夠?qū)⒋罅啃畔⒕幋a在小空間的編碼器。它是一種由黑白方塊構(gòu)成的圖片,可以將文本、鏈接、圖像等不同類型的信息編碼到其中。二維碼已經(jīng)廣泛應(yīng)用于不同的領(lǐng)域,如電子支付、電子門票、商品銷售等,這種快捷、高效的信息處理方式已成為現(xiàn)代生活中不可或缺的一部分。
所需依賴
<!-- 二維碼生成 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.5.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-mock --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-mock</artifactId> <version>2.0.8</version> <scope>compile</scope> </dependency>
主要代碼
需要用到的一些常量
/** 字符編碼 */
private static final String CHARSET = "utf-8";
/** 圖片格式 */
private static final String FORMAT_NAME = "JPG";
/** 二維碼尺寸 */
private static final Integer QRCODE_SIZE = 380;
/** LOGO寬度 */
private static final Integer WIDTH = 100;
/** LOGO高度 */
private static final Integer HEIGHT = 100;
生成二維碼
/**
* 生成二維碼,得到 MultipartFile--通用
* @param jsonString 二維碼內(nèi)容
* @param logoPath logo路徑
* @param bottomText 底部文字
* @return {@link MultipartFile}
* @ver v1.0.0
*/
public static MultipartFile createQrCode(String jsonString, String logoPath, String bottomText) throws Exception {
return initMultipartFile(jsonString, logoPath, bottomText);
}
/**
* 生成二維碼,得到 MultipartFile-有l(wèi)ogo、無底部文字
* @param jsonString 二維碼內(nèi)容
* @param logoPath logo路徑
* @return {@link MultipartFile}
* @ver v1.0.0
*/
public static MultipartFile createQrCode(String jsonString, String logoPath) throws Exception {
return initMultipartFile(jsonString, logoPath, null);
}
/**
* 生成二維碼,得到 MultipartFile-無logo、無底部文字
* @param jsonString 二維碼內(nèi)容
* @return {@link MultipartFile}
* @ver v1.0.0
*/
public static MultipartFile createQrCode(String jsonString) throws Exception {
return initMultipartFile(jsonString, null, null);
}
/**
* 生成二維碼
* @param content 二維碼內(nèi)容
* @param logoPath logo路徑
* @param bottomText 底部文字
* @return {@link MultipartFile}
* @ver v1.0.0
*/
private static MultipartFile initMultipartFile(String content, String logoPath, String bottomText) throws Exception {
//二維碼名稱
String qrName = "qr" + System.currentTimeMillis() + ".jpg";
int height = 0;
if (StringUtils.hasText(bottomText)) {
height = 10;
}
//得到BufferedImage對(duì)象
BufferedImage bufferedImage = createImage(content, logoPath, true, height);
// 判斷是否添加底部文字
if (StringUtils.hasText(bottomText)) {
addBottomText(bufferedImage, bottomText);
}
//創(chuàng)建一個(gè)ByteArrayOutputStream
ByteArrayOutputStream os = new ByteArrayOutputStream();
//把BufferedImage寫入ByteArrayOutputStream
ImageIO.write(bufferedImage, "jpg", os);
//ByteArrayOutputStream轉(zhuǎn)成InputStream
InputStream input = new ByteArrayInputStream(os.toByteArray());
//InputStream轉(zhuǎn)成MultipartFile
return new MockMultipartFile("qrFile", qrName, "text/plain", input);
}
/**
* 生成 BufferedImage
* @param content 存放在二維碼中的內(nèi)容
* @param imgPath logo的路徑及名稱
* @param needCompress 是否需要壓縮
* @param height 額外高度(有底部文字時(shí))
* @return {@link BufferedImage}
* @ver v1.0.0
*/
private static BufferedImage createImage(String content, String imgPath, boolean needCompress, int height) throws Exception {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter()
.encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int bitWidth = bitMatrix.getWidth();
int bitHeight = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(bitWidth, bitHeight + height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < bitWidth; x++) {
for (int y = 0; y < bitHeight; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入logo圖片
insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入logo圖片
* @param source 二維碼
* @param logoPath logo的路徑及名稱
* @param needCompress 是否需要壓縮
* @ver v1.0.0
*/
private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
File file = new File(logoPath);
if (!file.exists()) {
log.error(logoPath + " 該文件不存在!");
return;
}
Image src = ImageIO.read(new File(logoPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
// 壓縮LOGO
if (needCompress) {
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
// 繪制縮小后的圖
g.drawImage(image, 0, 0, null);
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 二維碼底部添加文字
* @param source 二維碼
* @param bottomText 底部文字
* @ver v1.0.0
*/
private static void addBottomText(BufferedImage source, String bottomText) {
//生成image
int defineWidth = QRCODE_SIZE;
int defineHeight = 20;
BufferedImage textImage = new BufferedImage(defineWidth, defineHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) textImage.getGraphics();
//開啟文字抗鋸齒
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setBackground(Color.WHITE);
g2.clearRect(0, 0, defineWidth, defineHeight);
g2.setPaint(Color.BLACK);
FontRenderContext context = g2.getFontRenderContext();
//部署linux需要注意 linux無此字體會(huì)顯示方塊
Font font = new Font("微軟雅黑", Font.BOLD, 15);
g2.setFont(font);
LineMetrics lineMetrics = font.getLineMetrics(bottomText, context);
FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
Rectangle rec = font.getStringBounds(bottomText, frc).getBounds();
double fontWidth = rec.getWidth();
double offset = (defineWidth - fontWidth) / 2;
float y = (defineHeight + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;
g2.drawString(bottomText, (int) offset, (int) y);
Graphics2D graph = source.createGraphics();
//開啟文字抗鋸齒
graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//添加image
int width = textImage.getWidth(null);
int height = textImage.getHeight(null);
graph.drawImage(textImage, 0, QRCODE_SIZE - 8, width, height, Color.WHITE, null);
graph.dispose();
}
二維碼解析
/**
* 根據(jù)二維碼路徑解析二維碼
* @param path 二維碼路徑
* @return {@link String}
* @ver v1.0.0
*/
public static String decode(String path) throws Exception {
return decode(new File(path));
}
/**
* 根據(jù)二維碼文件解析二維碼
* @param file 二維碼文件
* @return {@link String}
* @ver v1.0.0
*/
public static String decode(File file) throws Exception {
BufferedImage image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
是不是很簡(jiǎn)單0.0 好了,到這就結(jié)束啦!??!
以上就是Java生成與解析二維碼的完整指南的詳細(xì)內(nèi)容,更多關(guān)于Java生成與解析二維碼的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Java classloader類加載器的實(shí)現(xiàn)
本文介紹了Java類加載器的繼承性和隔離性,類加載器分為四個(gè)層級(jí):Bootstrap、Extension、System和Plugin,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-12-12
詳解java操作Redis數(shù)據(jù)庫(kù)的redis工具(RedisUtil,jedis工具JedisUtil,JedisPoo
這篇文章主要介紹了java操作Redis數(shù)據(jù)庫(kù)的redis工具,包括RedisUtil,jedis工具JedisUtil,JedisPoolUtil工具,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08
簡(jiǎn)單了解springboot eureka交流機(jī)制
這篇文章主要介紹了簡(jiǎn)單了解springboot eureka交流機(jī)制,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
???????Spring多租戶數(shù)據(jù)源管理 AbstractRoutingDataSource
本文技術(shù)了???????Spring多租戶數(shù)據(jù)源管理 AbstractRoutingDataSource,下文詳細(xì)內(nèi)容介紹,需要的小伙伴可以參考一下2022-05-05

