Java實(shí)現(xiàn)生成二維碼展示到瀏覽器的示例代碼
要實(shí)現(xiàn)在瀏覽器展示二維碼,那么首先需要html文件,通過(guò)Java生成二維碼的工具類,在controller層調(diào)用接口,就可以實(shí)現(xiàn)在瀏覽器上展示二維碼。
html文件內(nèi)容如下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:http="http://www.w3.org/1999/xhtml" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"> <head> <meta charset="UTF-8"> <title>二維碼</title> <script th:src="@{../js/jquery-3.1.1.js}"></script> <style type="text/css"> #qrcode-mask{ margin-left: 40px; margin-top: 30px; } #code-panel{ width: 280px; height: 320px; border: 1px solid #e1e1e1; margin: 0 auto; margin-top: 30px; background-color: rgba(255,215,255,0.25); box-shadow: -4px -4px 6px rgba(0,0,0,0.35) inset; } /*rgba(25,252,205,0.15);*/ #desc{ color: #717375; font-size: 14px; text-align: center; } </style> <script type="text/javascript"> onload=function(){ $.ajax({ type: 'POST', url: '/qrcode/img', dataType: 'json', data: '', success:function (result) { if (result.code == 1){ $("#qrcode").attr('src','data:image/png;base64,'+result.data.img); }else{ alert(result.info); } }, error:function (result) { alert("獲取失敗"); } }); } </script> </head> <body> <div id="code-panel"> <div id="qrcode-mask"> <img id="qrcode" alt="" src=""> </div> <div id="desc"> 掃描并關(guān)注<br> 微信公眾平臺(tái) </div> </div> </body> </html>
接著在Controller層實(shí)現(xiàn)一個(gè)接口,代碼如下:
import java.util.HashMap; import java.util.Map; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.suntree.commons.ApiResult; import com.suntree.utils.QRCodeUtil; @SpringBootApplication @RestController @RequestMapping("/qrcode") public class QRCodeContoller { /** * 獲取二維碼圖片 * @return */ @PostMapping("/img") public ApiResult getQRCodeImage() { ApiResult result=new ApiResult(); Map<String,Object> img=new HashMap<>(); String content="https://guangz-myblog.oss-cn-shenzhen.aliyuncs.com/private/user/%E5%88%98%E5%85%89%E5%AE%97/ff52da04-009d-49b4-9601-936c33bb0673.png"; String imgPath="https://guangz-myblog.oss-cn-shenzhen.aliyuncs.com/private/user/%E5%88%98%E5%85%89%E5%AE%97/ff52da04-009d-49b4-9601-936c33bb0673.png"; String base64=QRCodeUtil.getImageToBase64(content, imgPath, true); img.put("img", base64); return result.success(img); } }
這個(gè)獲取的是二維碼圖片的base64;
再接下來(lái)就是實(shí)現(xiàn)生成二維碼的工具類,代碼如下:
import java.awt.BasicStroke; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Shape; import java.awt.geom.RoundRectangle2D; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.Result; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import sun.misc.BASE64Encoder; public class QRCodeUtil { private static final String CHARSET = "utf-8"; private static final String FORMAT_NAME = "PNG"; // 二維碼尺寸 private static final int QRCODE_SIZE = 200; // LOGO寬度 private static final int WIDTH = 60; // LOGO高度 private static final int HEIGHT = 60; /** * 創(chuàng)建圖片 * @param content * @param imgPath * @param needCompress * @return * @throws Exception */ private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception { Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType, Object>(); 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 width = bitMatrix.getWidth(); int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); } } if (imgPath == null || "".equals(imgPath)) { return image; } // 插入圖片 QRCodeUtil.insertImage(image, imgPath, needCompress); return image; } /** * 插入圖片 * @param source * @param imgPath * @param needCompress * @throws Exception */ private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception { File file = new File(imgPath); if (!file.exists()) { System.err.println("" + imgPath + " 該文件不存在!"); return; } Image src = ImageIO.read(file); int width = src.getWidth(null); int height = src.getHeight(null); if (needCompress) { // 壓縮LOGO 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(); Graphics2D g2 = (Graphics2D) tag.getGraphics(); g2.drawImage(image, 0, 0, null); // 繪制縮小后的圖 g2.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 content * @param imgPath * @param destPath * @param needCompress * @throws Exception */ public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception { BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress); mkdirs(destPath); ImageIO.write(image, FORMAT_NAME, new File(destPath)); } public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception { BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress); return image; } public static void mkdirs(String destPath) { File file = new File(destPath); // 當(dāng)文件夾不存在時(shí),mkdirs會(huì)自動(dòng)創(chuàng)建多層目錄,區(qū)別于mkdir.(mkdir如果父目錄不存在則會(huì)拋出異常) if (!file.exists() && !file.isDirectory()) { file.mkdirs(); } } public static void encode(String content, String imgPath, String destPath) throws Exception { QRCodeUtil.encode(content, imgPath, destPath, false); } public static void encode(String content, String destPath) throws Exception { QRCodeUtil.encode(content, null, destPath, false); } public static void encode(String content, String imgPath, OutputStream output, boolean needCompress) throws Exception { BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress); ImageIO.write(image, FORMAT_NAME, output); } public static void encode(String content, OutputStream output) throws Exception { QRCodeUtil.encode(content, null, output, false); } public static String decode(File file) throws Exception { BufferedImage image; image = ImageIO.read(file); if (image == null) { return null; } BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); Result result; Map<DecodeHintType,Object> hints = new HashMap<DecodeHintType, Object>(); hints.put(DecodeHintType.CHARACTER_SET, CHARSET); result = new MultiFormatReader().decode(bitmap, hints); String resultStr = result.getText(); return resultStr; } /** * 生成二維碼圖片轉(zhuǎn)base64 * * @param content * @param imgPath * @param needCompress * @return */ public static String getImageToBase64(String content, String imgPath, boolean needCompress) { ByteArrayOutputStream out=null; try { BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress); out = new ByteArrayOutputStream(); ImageIO.write(image,"png",out); byte[] b = out.toByteArray(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(b);//生成base64編碼 } catch (Exception e) { e.printStackTrace(); }finally{ if(out!=null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } }
最后實(shí)現(xiàn)WebMvcConfigurer接口,這樣就可以在瀏覽器上展示二維碼了。
大家可以自己去試試,望大家多多支持!
到此這篇關(guān)于Java實(shí)現(xiàn)生成二維碼展示到瀏覽器的示例代碼的文章就介紹到這了,更多相關(guān)Java生成二維碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot如何讀取mock數(shù)據(jù)(高效調(diào)試接口)
本文介紹如何在SpringBoot項(xiàng)目中讀取resources目錄下的mock數(shù)據(jù)文件,以便高效調(diào)試接口,在 Spring Boot 項(xiàng)目中,通常會(huì)將靜態(tài)資源或配置文件放在 src/main/resources 目錄下,下面通過(guò)實(shí)例給大家詳細(xì)介紹,感興趣的朋友一起看看吧2024-12-12聊聊Spring?Cloud?Gateway過(guò)濾器精確控制異常返回問(wèn)題
這篇文章主要介紹了Spring?Cloud?Gateway過(guò)濾器精確控制異常返回問(wèn)題,本篇任務(wù)就是分析上述現(xiàn)象的原因,通過(guò)閱讀源碼搞清楚返回碼和響應(yīng)body生成的具體邏輯,需要的朋友可以參考下2021-11-11SpringBoot實(shí)現(xiàn)評(píng)論回復(fù)功能(數(shù)據(jù)庫(kù)設(shè)計(jì))
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)評(píng)論回復(fù)功能(數(shù)據(jù)庫(kù)設(shè)計(jì)),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04SpringBoot+Quartz實(shí)現(xiàn)定時(shí)任務(wù)的代碼模版分享
quartz?是一款開源且豐富特性的Java?任務(wù)調(diào)度庫(kù),用于實(shí)現(xiàn)任務(wù)調(diào)度和定時(shí)任務(wù),本文主要和大家分享一個(gè)SpringBoot整合Quartz實(shí)現(xiàn)定時(shí)任務(wù)的代碼模版,需要的可以參考一下2023-06-06SpringBoot使用JWT實(shí)現(xiàn)登錄驗(yàn)證的方法示例
這篇文章主要介紹了SpringBoot使用JWT實(shí)現(xiàn)登錄驗(yàn)證的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06SpringCloud Sleuth實(shí)現(xiàn)分布式請(qǐng)求鏈路跟蹤流程詳解
這篇文章主要介紹了SpringCloud Sleuth實(shí)現(xiàn)分布式請(qǐng)求鏈路跟蹤流程,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-11-11Java把數(shù)字格式化為貨幣字符串實(shí)例代碼
這篇文章主要介紹了Java把數(shù)字格式化為貨幣字符串實(shí)例代碼,需要的朋友可以參考下2014-02-02Java SpringBoot實(shí)現(xiàn)文件上傳功能的示例代碼
這篇文章主要介紹了如何利用Java SpringBoot實(shí)現(xiàn)文件上傳功能,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)有一定幫助,需要的可以參考一下2022-03-03SpringBoot2底層注解@Configuration配置類詳解
這篇文章主要為大家介紹了SpringBoot2底層注解@Configuration配置類詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05