使用Zxing二维码生成(第二种)
1、引用依赖
1 2 3 4 5 6 7 8 9 10 | <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version> </dependency><br> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.11</version> </dependency> |
2、测试生成二维码
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 44 45 46 47 48 49 50 51 52 | import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.google.zxing.client.j2se.MatrixToImageWriter; @RestController public class TestController { // 生成二维码 @RequestMapping( "/getCode" ) public void getCode(HttpServletResponse response){ // 二维码内容 String contents = "测试二维码" ; // 表示是二维码 BarcodeFormat qrCode = BarcodeFormat.QR_CODE; // 二维码宽度 int width = 300; // 二维码高度 int height = 300; // 返回的图片格式 String format = "png" ; response.setContentType( "image/png" ); try { Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); // 设置二维码编字符集 hints.put(EncodeHintType.CHARACTER_SET, "utf-8" ); // 设置二维码的外间距 hints.put(EncodeHintType.MARGIN, 10); // 设置二维码容错级别 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 创建二维码对象 BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, qrCode, width, height, hints); // 输出二维码 MatrixToImageWriter.writeToStream(bitMatrix, format, response.getOutputStream()); } catch (WriterException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
参考:https://www.cnblogs.com/jiangyalin/p/17085249.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!