在我以前的一篇文章中 ,我们了解了如何使用Zxing Java库创建QRCode及其等效的SVG。 Zxing库不再得到积极维护,为此,Zxing库周围有一个名为QRGen的包装,该包装提供了更高级别的API和用于生成QR代码的构建器语法。
在本文中,我们将看到如何使用QRGen库生成QR码图像。
设置Maven依赖项
QRGen库位于Mulesoft Maven存储库中。 您可以使用以下pom条目将其包括在应用程序依赖项中:
<dependencies><!-- https://mvnrepository.com/artifact/com.github.kenglxn.qrgen/javase --><dependency><groupId>com.github.kenglxn.qrgen</groupId><artifactId>javase</artifactId><version>2.5.0</version></dependency>
</dependencies><repositories><repository><id>mulesoft</id><url>https://repository.mulesoft.org/nexus/content/repositories/public/</url></repository>
</repositories>用于QR代码生成的Fluent Builder API
 下面的代码片段显示了QR码图像的生成,默认情况下,它是在临时文件中创建的,我们使用Files.copy()
 File file = QRCode.from( "www.google.com" ).to(ImageType.PNG) File file = QRCode.from( ).to(ImageType.PNG) .withSize( 200 , 200 ) .file();  String fileName = "qrgen-qrcode.png" ;  Path path = Paths.get(fileName);  if ( Files.exists(path)){ Files.delete(path);  }  Files.copy(file.toPath(), path); 彩色QR码
使用流畅的API,我们甚至可以生成彩色的QR代码,如下所示:
 Path colorPath = Paths.get( "qrgen-color-qrcode.png" );  if ( Files.exists(colorPath)){ Files.delete(colorPath);  }  file = QRCode.from( "www.google.com" ) .withColor(Color.RED.getRGB(), Color.WHITE.getRGB()) .withSize( 200 , 200 ) .withErrorCorrection(ErrorCorrectionLevel.Q) .file();  Files.copy(file.toPath(), colorPath); 完整的代码可以从这里下载。
翻译自: https://www.javacodegeeks.com/2019/04/create-qrcode-using-qrgen-java.html